Python offers different ways to substring a string and is often called as ‘slicing’.
It follows below template:
string[start: end: step]
Where,
start: The starting index of the substring. If start is not mentioned, it is supposed to be equal to 0.
end: The terminating index of the substring. If end is not mentioned,it is default be equal to the length of the string by default.
step:Indicates every ‘step’ character after the current character. The default value is 1.
Example 1:
Below is the code to get the first 5 characters of a string
string = "i2tutorials" print(string[:5])
Output:
i2tut
Note: print(string[:5]) is same as print(string[0:5]) and provides the same result.
Example 2:
Below is the code to get a substring of length 4 from the 3rd character of the string
string = “i2tutorials” print(string[2:6])
Output:
tuto
Example 3:
Below code results the last character of the string
string = "i2tutorials" print(string[-1])
Output:
s
Example 4:
Code to get the last 5 characters of a string
string = "i2tutorials" print(string[-5:])
Output:
rials
Example 5:
Below example results a substring which contains all characters except the last 4 characters and the 1st character
string = "i2tutorials" print(string[1:-4])
Output:
2tutor
Example 6:
Get every other character from a string
string = "i2tutorials" print(string[::2])
Output:
ittras
Example 7:
Getting substring by picking the element after certain position gap
string = "i2tutorials" print(string[2:9:2])
Output:
ttra