Python Slicing Strings

Slicing lets you pull out a portion of a string by specifying a start and stop position.

Indexing Basics

Every character in a string has a position called an index. Python counts from zero, so the first character sits at index 0, the second at index 1, and so on. You can read a single character by putting its index in square brackets after the string.

Reading one character

text = "Python"

print(text[0])
print(text[2])
print(text[-1])

Negative indexes count backwards from the end. Index -1 is the last character, -2 is the one before it, and so on. This is a quick way to reach the tail of a string without knowing its length.

The Slice Syntax

A slice uses the form text[start:stop]. It returns every character from the start index up to, but not including, the stop index. If you leave out the start it defaults to the beginning, and if you leave out the stop it runs to the end.

Taking slices

text = "Programming"

print(text[0:4])
print(text[4:])
print(text[:7])
print(text[-4:])
Note: The stop position is exclusive. text[0:4] returns four characters at positions 0, 1, 2, and 3 - never the character at index 4. Forgetting this off-by-one detail is a common beginner mistake.

Slicing With a Step

A third value, the step, controls how many positions to jump between characters: text[start:stop:step]. A step of 2 takes every second character, and a negative step walks through the string in reverse, which gives a neat way to flip a string.

Step and reverse

text = "abcdefgh"

print(text[::2])
print(text[1::2])
print(text[::-1])
ExpressionResultMeaning
text[2:5]'cde'Characters from index 2 up to 5
text[:3]'abc'From the start through index 2
text[3:]'defgh'From index 3 to the end
text[::-1]'hgfedcba'The whole string reversed