Sunday, August 29, 2010

Programming in Python : Strings

Strings are also manupulated by python. Strings are represented within single quotes or double quotes. We can assign a string to a variable, and printed by using 'print'. Strings can be surrounded by triple quotes """. If there is \n the end of line, is echoed in the output.

>>> "Hello"+"world"
'Helloworld'

>>> a='how are you?'

>>> print a
how are you?

The slice notation :

The slice notation is used to return the elements of a list or characters of a string as specified by the indices.

>>> string1 = 'hello world'

>>> string1
'hello world'

>>> string1[0:1]
'h'

>>> string1[0:4]
'hell'

>>> string1[2:4]
'll'

>>> string1[:4]
'hell'

>>> string1[3:]
'lo world'

>>> string1[:0] = 'Hai'
Traceback (most recent call last):
File "", line 1, in
TypeError: 'str' object does not support item assignment

>>> string1[:0] + 'Hai'
'Hai'

>>> string1
'hello world'

>>> string1[:] + 'Hai'
'hello worldHai'

>>> 'Hai' + string1[:]
'Haihello world'

The negative indices are using to indicate from the right to the begining of the string.

>>> string1[-1]
'd'

>>> string1[-4:-1]
'orl'

>>> string1[-4:-2]
'or'

>>> string1[-4:0]
''

>>> string1[-1:-4]
''

>>> string1[-11:-1]
'hello worl'

No comments:

Post a Comment