🎓 A1Learner
🔍

Python String Indexing

String indexing picks one character from a string by its position number. The first character sits at index 0.

The first character

Index 0 gives the first character.

word = "Python"
print(word[0])

Other positions

Count from zero as you move right.

word = "Python"
print(word[1])
print(word[4])

The last character

Index -1 gives the last character. You do not need to know the length first.

word = "Python"
print(word[-1])

Count back from the end

Negative indexes move left from the end.

word = "Python"
print(word[-2])
print(word[-6])

An index that is too big

This word has indexes 0 to 5 only. Index 10 does not exist.

word = "Python"
print(word[10])

Example

word = "program"
print(word[0])
print(word[-1])
print(word[3])

Key points

  • Index: the position number of a character in a string
  • The first character is at index 0, not index 1
  • Use square brackets to get one character, like s[0]
  • A negative index counts back from the end
  • Index -1 is always the last character

In this example, word holds the text program. word[0] gives the first letter, p. word[-1] gives the last letter, m. The word has seven letters, so the middle sits at index 3. word[3] gives the middle letter, g.

Note

Asking for an index that is too big raises IndexError.

Python stops instead of guessing a character.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What is word[2] when word = "cat"?