← Intro to programming with Python

Picking out characters: indexing and slicing

Grab one letter, or a piece of a string.

Start this lesson

Each character in a string has a position number called its index. Python starts counting at 0, because the index means "how many steps from the start": the first letter is 0 steps away. So word[0] is the first character, and word[-1] counts from the end and gives the last. len(word) tells you how many characters there are. To take a piece (a slice), write word[start:stop]. It starts at start and stops just BEFORE stop.

word = "Python"
print(len(word))    # 6
print(word[0])      # P
print(word[-1])     # n
print(word[0:3])    # Pyt
print(word[2:])     # thon

word[0:3] takes positions 0, 1 and 2, which is 3 characters. Leaving out the stop, as in word[2:], means "to the end".

Common mistake: asking for word[6] in a 6-letter word. The positions are 0 to 5, so you get an IndexError ("string index out of range"). The last index is always len(word) - 1.

A nice fact about slices: word[a:b] always has b - a characters.

Spaces and punctuation are characters too, and they have positions.