Substrings
Often, we only need a specific portion of the string stored in a
str variable, and
Python comes to our aid! Similar to accessing
a single character in the string, by using indices and the colon operator "
:", we can easily
obtain
a substring:
string[start_index : end_index[ : step]]
EXAMPLES
Note! The last character specified by the index is not included!
We displayed the characters from indices
3 to
8, then from
15 to
20 (write the last desired index,
+1):
(translation in English: "There is snow in Sinaia!")
DETAILS
The variable
s2 holds the string "
Sinaia", then the string
s3 holds the first three characters, namely "
Sin",
which we display along with the rest of the
print() function content, with the default space separator:
If we choose the step
-1 and leave the other attributes empty (
s1[::-1]), the string will be displayed
from right to left (its
reverse):
Run the program, then proceed to the next page.