Hacking Secret Ciphers with Python

(Ann) #1
Chapter 4 – Strings and Writing Programs 45

'Hello'





'Hello world!'[6:12]
'world!'
'Hello world!'[-6:-1]
'world'
'Hello world!'[6:12][2]
'r'





Notice that the expression 'Hello world!'[6:12][2] first evaluates to 'world!'[2]
which is an indexing that further evaluates to 'r'.


Unlike indexes, slicing will never give you an error if you give it too large of an index for the
string. It will just return the widest matching slice it can:





'Hello'[0:999]
'Hello'
'Hello'[2:999]
'llo'
'Hello'[1000:2000]
''





The expression 'Hello'[1000:2000] returns a blank string because the index 1000 is after
the end of the string, so there are no possible characters this slice could include.


Blank Slice Indexes....................................................................................................................................................


If you leave out the first index of a slice, Python will automatically think you want to specify
index 0 for the first index. The expressions 'Howdy'[0:3] and 'Howdy'[:3] evaluate the
same string:





'Howdy'[:3]
'How'
'Howdy'[0:3]
'How'





If you leave out the second index, Python will automatically think you want to specify the rest of
the string:





'Howdy'[2:]
'wdy'




Free download pdf