String slicing allows you to extract a portion of a string.
It takes two parameters: the starting index and the ending index (optional). It returns a new string containing the extracted portion.
Let's perform such operations on the string "computer". Its structure is the following:
Output:
In this example, str[3:]
skips the first 3
symbols of the string - c
, o
, and m
.
The rest of the string (starting from the 3rd index - p
) is extracted - puter
.
Negative indexes track the string characters in reverse.
Output:
In this example, str[-3:]
extracts only the last 3 symbols of the string - t
, e
, and r
.
Output:
In this example, str[3:5]
skips the first 3
symbols of the string - c
, o
, and m
.
Then it takes the rest of the string until it reaches the 5th symbol - u
.
Output:
In this example, str[-5:-2]
starts slicing at the 5th symbol counting backwards and ends before the second symbol counting backwards.
Both positive and negative arguments can be specified.
Output:
In this example, str[1:-1]
starts after the first symbol and ends before the last symbol.
An invalid case simply returns an empty string. In such cases, the slicing start argument position is after the slicing end.
Example of a valid and invalid case:
Output:
Another invalid slicing case is specifying a starting argument that's beyond the string's bounds:
Output:
The third argumen allows you to specify an additional step (also known as the stride) to skip characters in the range while slicing.
Output:
In this example 3
specifies that every 3rd symbol of the string must be extracted.
It can be combined with the other arguments to slice only in a certain range and with specific step:
Output:
In this case the first argument (5) skips the first 5 symbols - -----
.
The second argument (-5) skips the last 5 symbols - *****
.
The third argument takes every 3rd symbol of the sliced string (smartphone
) - s, r, h and e.