Page 263 - Computer Science Class 11 Without Functions
P. 263
id(s): 1631127097456 s: abcdefghijabcdefghij
id(s): 1631127097456 s: abcdefghijabcdefghij
Note that even though the variable s finally denotes the string abcdefghijabcdefghij, the control exits the
for-loop on processing the characters of the initial string s: abcdefghij. Also, note that when a string object has
outlived its purpose, Python may not create a new object id for another string object. Thus, the strings, 'abcdefghij',
'abcdefghijab', 'abcdefghijabc', 'abcdefghijabcd', and 'abcdefghijabcde' have the
same object id. However, it is not a general rule, and the strings 'abcdefghijabcde' and 'abcdefghijabcdef'
have different object ids. As a general rule, we should avoid such obfuscated codes.
Never modify the value of a control variable inside a for-loop.
Transforming Numerical Values to Strings: A numerical value may be transformed into a string using the str()
function. For example,
>>> 'I want' + str(2) + 'cups of ice cream.'
' I want 2 cups of ice cream.'
Membership operator in: Examine the membership of a particular character or a substring in the given string using
the membership operator in.
str(): To transform a data object to a string.
11.3 String Slices
Often, we are interested in extracting/accessing more than one character, i.e. a subsequence of characters from the
string. For example, we may be looking for the last name of an employee, or we may be interested in a name beginning
with Abhishek. A subsequence of characters in a string is called a slice. A slice is marked by specifying the start and
finish indices using the notation: <start>:<finish>. 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,
Strings 261

