3.6.4. Indexing and slicing strings#
We learned how to index and slice lists. The exact same behaviour applies to strings: we can extract one or many characters from a string by slicing it:
string = "This is a sample string that we will index and slice"
# Get the first character
print(string[0])
# Get the last character
print(string[-1])
# Get the 10 first characters
print(string[:10])
# Get the 10 last characters
print(string[-10:])
# Get every other character
print(string[::2])
T
e
This is a
and slice
Ti sasml tigta ewl ne n lc