>>> "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 "
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