Page 309 - Computer Science Class 11 With Functions
P. 309
For example,
>>> 'excellent'[2:4]
'ce'
Note that a slice includes all characters in the string beginning with the start index (2 in the above example) and up
to the finish index (4 in the above example), including the character at the start index, but excluding the character at
the finish index. While using non-negative indices, if the finish index of a slice is lower than or equal to the start
index, Python yields the null string '', for example,
>>> 'excellent'[4:0]
''
>>> 'excellent'[3:3]
''
Now let us consider another example,
>>> 'excellent'[-5:0]
''
Although the index -5 is numerically less than the index 0, the expression 'excellent'[-5:0] still yields a null
string because the index 0 occurs before the index -5. For example,
>>> 'excellent'[–4:–1]
'len'
The slice 'excellent'[-4:-1] includes all characters beginning with the one at index -4 (l), up to index -1,
excluding the character at index -1.
>>> 'excellent'[–1:–4]
''
As we cannot count up from -1 to -4. Python yields a null string for the slice 'excellent'[-1:-4]. However, it
is fine to mix negative and non-negative indices while defining a slice, for example,
>>> 'excellent'[3:–1]
'ellen'
>>> 'excellent'[3:8]
'ellen'
Note that the slice [3:-1] includes the characters at indices, 3, 4, 5, 6, 7 because index 8 is the same as
index -1. So, Python interprets the slice [3:-1] as the slice [3:8]. Sometimes, we leave the start index or finish
index unspecified. Python substitutes 0 for the unspecified start index and the length of the string for the unspecified
finish index. For example,
>>> 'excellent'[-9:]
'excellent'
>>> 'excellent'[-7:]
'cellent'
>>> 'excellent'[2:]
'cellent'
>>> 'excellent'[:6]
'excell'
If the start index specified in a slice lies beyond the valid range of indices, it is replaced with the index 0. For example,
>>> 'excellent'[-12:6]
'excell'
Similarly, if the finish index specified in a slice is beyond the allowable range, it is replaced by the length of the string.
If it is less than the least valid index, it is replaced with the index 0. For example,
>>> 'excellent'[-12:26]
'excellent'
>>> 'excellent'[1:26]
'xcellent'
>>> 'excellent'[:]
'excellent'
Strings 307

