Sub topic 2
Slicing with Start and Stop
Assume you know string variables, print(), len(), and basic try/except. A slice is a new string made from part of an existing string. Its basic form is:
text[start:stop]The start index is included, but the stop index is excluded.
s = "Python"
print(s[0:2]) # Py
print(s[2:5]) # thoThe first slice uses indexes 0 and 1. The second uses indexes 2, 3, and 4.
Leaving Out Start or Stop
You can omit either bound. An omitted start means “from the beginning.” An omitted stop means “through the end.”
s = "Python"
print(s[:3]) # Pyt
print(s[2:]) # thon
print(s[:]) # Python
print(s[-3:]) # honThe expression s[:] creates a new string with the same contents. For strings, this is usually unnecessary because strings cannot be changed in place.
Slices That Go Past the Ends
Slice bounds may be outside the valid index range. Python adjusts them to the nearest valid boundary instead of raising IndexError.
s = "Python"
print(s[2:100]) # thon
print(repr(s[10:])) # ''
print(repr(s[4:2])) # ''The last result is empty because the default direction is forward, but index 4 is already past index 2.
Skipping Characters with a Step
A slice can have a third value, called the step:
text[start:stop:step]It determines how far Python moves between selected indexes.
s = "abcdefghij"
print(s[::2]) # acegi
print(s[1::2]) # bdfhj
print(s[2:8:3]) # cfA step of 2 selects every second character. A negative step moves backward, so s[::-1] reverses the string.
Exercise
What does "Python"[1:6:2] produce?
Show answer
"yhn", using indexes 1, 3, and 5.