Slicing for substrings
In many situations, you might need a particular portion of strings such as the first three characters of the string. Python's subscript operator uses slicing. In slicing, colon :
is used. An integer value will appear on either side of the colon. Refer to the following example:
>>>Â
>>> name[0:3]
'The'
>>> name[:6]
'The Av'
>>> name[4:]
'Avengers'
>>> name[5:9]
'veng'
>>>
>>> name[::2]
'TeAegr'
>>>
Refer to the following diagram to clear your remaining doubts:
String positive and negative slicing
Note
If you want to print a reverse of the given string str1
, then use str1[::-1]
To find the length of a string, you can use the len()
function:
>>> len(name) 12 >>>Â
Now, let's see some useful string methods.