Strings are very easy to use in python.
There are four ways to write strings:
In [3]:
x = "Hello, Python!" # Enclosed in double quotes
print x
In [4]:
y = 'Hello, Python!' # Single quotes
print y
In [4]:
"""Hello, Python!""" # Triple quotes
Out[4]:
In [5]:
'''Hello, Python!''' # Triple quotes can use single quotes as well !
Out[5]:
As you can see, you get the same content in all three cases. Triple quotes allow entry of multi-line strings. Double-quote allows single quotes to be used freely inside the string. Using single quotes likewise allows double-quotes to be used in the string. Special characters need to be "escape"d, as in C.
In [2]:
'"And this too, shall pass"'
Out[2]:
In [3]:
"'And this too, shall pass'"
Out[3]:
Note that each string is actually a string object. This means that many operations are defined on the string.
In [9]:
s = "Hello, Python!"
dir(s)
Out[9]:
In [10]:
s.upper()
Out[10]:
In [11]:
s.lower()
Out[11]:
In [13]:
s.split(', ')
Out[13]:
In [14]:
s.startswith('Hello')
Out[14]:
In [21]:
len(s) # number of chars
Out[21]:
You may use the [] operator to extract parts of the string.
In [15]:
s[0]
Out[15]:
In [17]:
s[0:2]
Out[17]:
In [24]:
s[1:6]
Out[24]:
In [18]:
s[-1] # last char
Out[18]:
In [20]:
s[0:-2] # all but last char
Out[20]: