← Python lessons

Python String Slicing: Start, Stop, Step and Reverse

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A slice like text[0:4] takes part of a string. It gives you a new string and leaves the original unchanged.

You will learn to cut a piece out of a string, skip and reverse characters with a step, and build a changed copy of a string. Read Indexing first: this lesson assumes positions from 0, negative indexes and len(). Every example uses a fixed string, so Run prints the same output shown under it.

Take part of a string

text[start:stop] takes the characters from start up to, but not including, stop.

text = "programming"
print(text[0:4])
print(text[3:7])

This prints prog (positions 0 to 3) and gram (positions 3 to 6). The stop position is never included, so stop - start is the length of the slice.

Leave out start or stop

Leave out start to begin at 0. Leave out stop to run to the end. Negative numbers count from the end, as with indexes.

text = "programming"
print(text[:3])
print(text[3:])
print(text[-4:])

This prints pro, gramming and ming. text[:3] + text[3:] always rebuilds the whole string, because each character lands in exactly one half.

Slices never go out of range

An index past the end raises an error. A slice past the end just stops early.

code = "AB12"
print(code[:10])
print(code[10:] == "")
print(code[10])  # this line raises IndexError

code[:10] gives AB12 and code[10:] gives the empty string. Use a slice when the string may be shorter than you expect, like name[:3] for a short nickname. Use an index when a missing character should be an error.

Skip and reverse with a step

A third number is the step. text[::2] takes every second character. A negative step walks backwards, so text[::-1] is the string reversed.

text = "abcdefgh"
print(text[::2])
print(text[1::2])
print(text[::-1])
print(text[5:1:-1])

This prints aceg, bdfh, hgfedcba and fedc. With a negative step, start is the right-hand end and stop is the left, still excluded.

Strings can't be changed in place

A string is immutable: you can't assign to one position. Build a new string from slices instead and give it the same name.

word = "cat"
try:
    word[0] = "b"
except TypeError as error:
    print("TypeError:", error)
word = "b" + word[1:]
print(word)

word[0] = "b" fails with TypeError. "b" + word[1:] makes the new string bat. Lists are different: scores[0] = 15 changes a list in place.

See also: List slicing and joining.

Your turn

plate holds a number plate. Print its first three characters, its last three, the whole plate reversed, and a new plate with the middle hyphen replaced by a space. Use slices only, no string methods.

plate = "ABC-123"
# add four prints: first three, last three, reversed, and the first three + " " + the last three

Expected output

ABC
123
321-CBA
ABC 123