Chapters
Python114 chapters

StringsChapter 16 of 114

Slicing

Take a piece out of a string with start, stop and step.

start and stop

A slice takes a range of characters. The start is included, the stop is not:

Python
word = "programming"
print(word[0:3])
print(word[3:7])

Output

pro
gram

That "stop is not included" rule looks fussy and pays for itself: the length of word[a:b] is always b - a, and word[:n] plus word[n:] is always the whole thing.

Python
word = "programming"
print(len(word[2:7]))
print(word[:4] + word[4:] == word)

Output

5
True

Leaving an end off

Omit the start to begin at the beginning, and the stop to run to the end:

Python
word = "programming"
print(word[:3])
print(word[3:])
print(word[:])

Output

pro
gramming
programming

Negative positions

Negative numbers count from the right, in a slice just as in an index:

Python
filename = "report.pdf"
print(filename[-3:])
print(filename[:-4])

Output

pdf
report

The step

A third number says how big a stride to take:

Python
letters = "abcdefgh"
print(letters[::2])
print(letters[1::2])

Output

aceg
bdfh

A negative step walks backwards, which is the shortest way to reverse a string:

Python
print("stressed"[::-1])

Output

desserts

Slices never fail

Indexing past the end raises IndexError. Slicing past the end just gives you what is there, which makes slices safe on input you have not measured:

Python
word = "abc"
print(word[0:99])
print(word[10:20])
print(repr(word[10:20]))

Output

abc

''

The second line looks blank because it is an empty string.

Slicing works on any sequence

The same syntax applies to lists and tuples, which is why it is worth learning properly once:

Python
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4])
print(numbers[::-1])

Output

[1, 2, 3]
[5, 4, 3, 2, 1, 0]

Test yourself

3 questions

For word = "programming", what is word[0:3]?

Show the answer

"pro" — The start is included and the stop is not, so a slice a:b is always b - a long.

What does "abc"[::-1] give?

Show the answer

"cba" — A negative step walks backwards, which is the usual way to reverse a string.

What does "abc"[10:20] give?

Show the answer

An empty string — Slices never fail on out-of-range positions; only indexing does.

Next chapter

Modify Strings

Change case, trim whitespace and replace text - always by making a new string.