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


Hello, Python!

In [4]:
y = 'Hello, Python!' # Single quotes
print y


Hello, Python!

In [4]:
"""Hello, Python!""" # Triple quotes


Out[4]:
'Hello, Python!'

In [5]:
'''Hello, Python!''' # Triple quotes can use single quotes as well !


Out[5]:
'Hello, Python!'

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]:
'"And this too, shall pass"'

In [3]:
"'And this too, shall pass'"


Out[3]:
"'And this too, shall pass'"

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]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__getslice__',
 '__gt__',
 '__hash__',
 '__init__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '_formatter_field_name_split',
 '_formatter_parser',
 'capitalize',
 'center',
 'count',
 'decode',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'index',
 'isalnum',
 'isalpha',
 'isdigit',
 'islower',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']

In [10]:
s.upper()


Out[10]:
'HELLO, PYTHON!'

In [11]:
s.lower()


Out[11]:
'hello, python!'

In [13]:
s.split(', ')


Out[13]:
['Hello', 'Python!']

In [14]:
s.startswith('Hello')


Out[14]:
True

In [21]:
len(s) # number of chars


Out[21]:
14

You may use the [] operator to extract parts of the string.


In [15]:
s[0]


Out[15]:
'H'

In [17]:
s[0:2]


Out[17]:
'He'

In [24]:
s[1:6]


Out[24]:
'ello,'

In [18]:
s[-1] # last char


Out[18]:
'!'

In [20]:
s[0:-2] # all but last char


Out[20]:
'Hello, Pytho'