Extracting a Substring in Python
To extract a portion of a string in Python, we use slicing.
string[start position:end position:step]
The first parameter specifies the starting position of the substring within the string. The second parameter indicates the ending position. The step parameter is optional and defines the interval at which slicing is applied.
Practical Examples
Example 1
To extract the first six characters of the string, use the following code:
name="Andrea Minini"
print(name[:6])
The output will be:
Andrea
This slicing operation extracts the substring starting at position 0 and ending at position 6.
In slicing, the 0 can be omitted. So, writing [0:6] is the same as writing [:6].
Example 2
To extract the last six characters of the string, use this code:
name="Andrea Minini"
print(name[-6:])
The output will be:
Minini
Here, the slicing starts from the sixth character from the end and goes to the last character.
When there is a minus sign before the first parameter, slicing starts from the end of the string instead of the beginning.
Example 3
To extract every second character from the string, use this code:
name="Andrea Minini"
print(name[::2])
The output will be:
Ade iii
This command selects the first character (A), skips the second (n), selects the third (d), skips the fourth (r), selects the fifth (e), and so on.
And so on.