Write Python. Understand every error.

Open the editor

Error guide · TypeError

TypeError: string indices must be integers

You used text where a whole-number position was needed to pick a character.

Example

word = "Python"
position = "2"
print(word[position])

What Python says

TypeError: string indices must be integers, not 'str'

As printed by Python 3.12. Other versions may word it slightly differently.

Try this code in Py-CRAFT

Why it happens

A position in a string must be an integer. Here position holds the text "2", not the number 2. This often happens when the position comes from input(), which always returns text. Lists follow the same rule and give the message list indices must be integers or slices.

How to fix it

word = "Python"
position = int("2")
print(word[position])

Output: t

Tips

Learn the ideas behind it

Other common errors

Share this page: