Page 310 - Computer Science Class 11 With Functions
P. 310
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 the syntax and see 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>
Consider the string given below:
quote="Practice makes you Perfect"
Write the output for the following Python statements:
(i) quote[5:15]
(ii) quote[-5:10]
(iii) quote[-4:-15:3]
(iv) quote[-4:-15:-1]
(v) quote[4:10:2]
(vi) quote[10:]
(vii) quote[:10]
12.2.1 Constructing a New String by Replacing Parts of a String
In one of the previous examples, we were not able to change the string Kamal to Komal as the strings are immutable.
However, we may create a new string by replacing 'a' with 'o', i.e., by concatenating the following: character at
index 0, letter 'o', and the slice of the string beginning at index 2 and up to the end. Subsequently, the newly formed
string can be assigned to the existing variable name as follows:
>>> name = 'Kamal'
>>> id(name)
2594101581488
>>> name = name[0] + 'o' + name[2:]
308 Touchpad Computer Science-XI

