Slices
An index gives you one character. A slice gives you a piece of a string, a substring: text[start:end] takes the characters from the index start up to, but not including, the index end.
text = "basketball"
print(text[0:6])
print(text[6:10])
print(text[2:5])
basket
ball
skeIt helps to picture the indexes as marks between the characters, with the mark 0 before the first character. A slice takes what lies between two marks:
| b | a | s | k | e | t | b | a | l | l |
0 1 2 3 4 5 6 7 8 9 10
So text[0:6] is everything between the marks 0 and 6. Because the end is left out, the length of a slice is simply end - start: text[2:5] has 3 characters.
Leaving out the start or the end
Leave out the start, and the slice begins at the start of the string. Leave out the end, and it goes on to the end. Negative indexes work in slices too:
date = "2026-10-15"
print(date[:4])
print(date[5:7])
print(date[-2:])
2026
10
15date[:4] is the first four characters, and date[-2:] the last two.
Slices don't run out
Unlike an index, a slice that goes past the end of the string doesn't stop the program. It takes whatever characters there are, perhaps none at all:
word = "cat"
print(word[1:100])
print("[" + word[5:9] + "]")
at
[]A loop can move a slice along a string. This one prints a code in pieces of three characters; the last piece is shorter, since the slice stops at the end of the string:
code = "ABCDEFGH"
start = 0
while start < len(code):
print(code[start:start + 3])
start += 3
ABC
DEF
GH