Page 264 - Computer Science Class 11 Without Functions
P. 264
>>> '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:]
'excellent'
>>> 'excellent'[2:]
'excellent'
>>> '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]
'excellent'
>>> 'excellent' [ : ]
'excellent'
Finally, for any string s, s[:n] + s[n:] always yields, s, irrespective of the value of n, for example,
>>> 'excellent' [:6] + 'excellent'[6:]
'excellent'
>>> 'excellent'[:–6] + 'excellent'[-6:]
'excellent'
>>> 'excellent'[:26] + 'excellent'[26:]
'excellent'
Next, suppose we wish to print the alternate characters of the string, say, the first character followed by the third
character, the fifth character, and so on. This may be achieved using the third component- step of slicing. Thus, a slice
can be specified using the notation: <start>:<finish>:<step>,
Let's break down what each part of the syntax means:
● start: This is the index at which the slice begins. The character at this index is included in the slice.
● finish: This is the index where the slice ends. The character at this index is not included in the slice. The slice goes
up to, but does not include, the character at the "finish" index.
● step: This is an optional parameter that specifies the interval between characters to include in the slice. If omitted,
the default step is 1, meaning characters are included one by one. If you provide a value of 2, for instance, every
second character would be included in the slice. For example,
>>> 'excellent'[::2]
'eclet'
>>> 'excellent'[::-2]
'telce'
A slice is marked by specifying the start, finish, and step indices using the notation: <start>:<finish>:<step>
262 Touchpad Computer Science-XI

