Slicing in Python
One of the core features of the Python language is slicing, as it appears in many commands.
What is slicing? The term comes from the English word "to slice" (to cut into pieces). It involves dividing an object into numbered units in a sequential order. This can apply to both lists and characters in a string.
How to Use Slicing in Python
Consider an alphanumeric string containing the name "Andrea Minini."
This string consists of 13 characters.
Using slicing, the string is treated as a sequence of thirteen elements, each with its own position.
Position 0 marks the start of the string.
With this indexing, you can extract any substring by specifying its start and end positions.
For example, to extract the substring "rea" using slicing, you would write (3:6).
Example 1
To extract and display the substring from a variable, you would use the following script:
nome="andrea minini"
print(nome[3:6])
The output is:
rea
Slicing can also be done in reverse.
In this case, position -1 indicates the end of the last character of the string, and the numbering is negative, going from right to left.
To extract the same substring "rea" in this case, you would write (-10:-7).
The first position on the left always indicates the start of the substring.
Example 2
To extract and display the substring, you would use the following script:
nome="andrea minini"
print(nome[-10:-7])
The output remains:
rea
In these examples, we used a string.
However, slicing can also be applied to a list. In this case, the positions would refer to the elements of the list.
The principle behind slicing remains the same.