Slicing in Python
Slicing
Sometimes, we need to retrieve a substring, also called a slice, from a string. This can be done by specifying an index range. For example, to extract the substring comprising the character sequence having indices from start to end-1, we specify the range in the form start:end as illustrated below:
>>> message = 'Hello Sita'
>>> message [0:5]
'Hello'
>>> mesage[10: -5]
If the value of start or end is not specified. Python assumes 0 as the default value of start, and length of the string as the default value of end, for example;
>>> mesnage[:5]
'Hello'
Note that message[:n] + message [n:] always yields message, irrespective of the value of n being negative, positive, or even out of range. Indeed, values used for defining a slice may be arbitrary integers or even None, for example:
>>> message [18:20]
'ta'
>>> message [16:None]
'Sita'
Apart from extracting a consecutive subsequence of characters from a string. Python also allows us to extract a subsequence of the form start:end: ine. This subsequence will include every ineth element of the sequence in the range atart to end-1, for example:
>>> message [0:len (mensage):2]
'HloSt'
>>> message [0:len (message):3]
'HlSa'
We have already mentioned that a string is a sequence of characters. The sliging operation discussed above can also be applied to other sequences such as lists and tuples, to be discussed later.
Membership
Python also allows us to check for membership of the individual characters or substrings in strings using in operator. Thus, the expression a in stri yields True or False depending on whether s is a substring of str1, for example.
>>> 'h' in 'hello'
True
>>> 'ell' in 'hello'
True
>>> 'h' in 'Hello'
False
In Python, we use a for loop to iterate over each element in a sequence. In the following example, we construct the string 'hello' from the string 'hello' by iterating over each element of the string:
>>> helloSpaced = ''
for ch in 'hello':
helloSpaced hellospaced + ch + ''
>>> helloSpaced
'hello'
1 Response to "Slicing in Python"
Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing
Python Online Training in India
Python Online Training In Hyderabad
Post a Comment