This Slicing Strings lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
A slice uses start:end. The character at end is left out. Omit start to begin at the first character, or omit end to run through the last.
A third number is the step. A step of -1 walks the text backwards.
Example 1: Start here
Indexes start at 0. topic[0:2] is Py.
topic = "Python" # text
print(topic[0:2])
print(topic[2:])
print(topic[::-1])
Example 2: First three letters
The start is included. The stop is not, so you get Pyt.
word = "Python" # text
print(word[0:3])
Example 3: From the end
A negative index counts from the right. This prints hon.
word = "Python" # text
print(word[-3:])
Example 4: Every second letter
The third number is the step. The slice keeps P, t, and o.
word = "Python" # text
print(word[::2])
