Skip to content
FollowtheDamnCode

Indexing and Slicing

Getting one character, or a piece, by position.

4 minute read

Big idea

Every character in a string has a numbered position, its index, starting at 0. s[i] gets one character; s[start:stop] gets a slice.

Indexing

word = "Python"
Each character has two indexes: from the front and from the back

Counting starts at 0, so the last index is always len(word) - 1. Negative indexes count from the end: -1 is the last character.

One character at a time
word = "Python"
print(word[0])
print(word[3])
print(word[-1])
print(word[len(word) - 1])
output
P
h
n
n

Run and edit it in the app.

Asking for an index that doesn't exist — word[6] — stops the program with IndexError: string index out of range.

Slicing

s[start:stop] takes the characters from start up to but not including stop:

Predict: three slices
word = "Python"
print(word[0:2])
print(word[2:5])
print(word[-3:])
What does it print? Show the answer
Py
tho
hon

Run and edit it in the app.

Leave a side out and it runs to the edge:

  • s[:3] — the first 3 characters
  • s[3:] — everything from index 3 on
  • s[:] — a copy of the whole thing

The "up to but not including" rule has a nice property: s[:3] + s[3:] is always the whole string, and s[a:b] has exactly b - a characters.

Watch it

Steps

A third number sets the step. s[::2] takes every second character, and a step of -1 walks backwards — the shortest way to reverse a string:

Every other character, and backwards
letters = "abcdefgh"
print(letters[::2])
print(letters[::-1])
output
aceg
hgfedcba

Run and edit it in the app.

Strings can't be edited

Indexing reads characters; it can't change them:

Fix the bug: print "Jython"
word = "Python"
word[0] = "J"
print(word)
output
Jython

Run and edit it in the app.

Strings are immutable, so word[0] = "J" raises a TypeError. Build a new string instead: word = "J" + word[1:].

s = 'keyboard'. What is s[3:6]?

Think of it like

Seats in a row, numbered from 0. s[2:5] is "seats 2, 3, and 4" — the stop number is the first seat you don't take.

Key terms

  • Index — A character's position, starting at 0; negatives count from the end.
  • Slice — A piece of a string, s[start:stop:step].
  • IndexError — Asking for a position that doesn't exist.

Check yourself

s = 'hello'. What is s[0]?

s = 'hello'. What is s[-1]?

How do you reverse a string s?