TypeError: string indices must be integers in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: string indices must be integers in Python #

The Python "TypeError: string indices must be integers" occurs when we use a non-integer value to access a string at an index. To solve the error, make sure to use an integer, e.g. my_str[2] or a slice, e.g. my_str[0:3] when accessing a string at a specific index.

typeerror string indices must be integers

Here is an example of how the error occurs.

main.py
my_str = 'hello' # 👇️ this is also a string my_index = '1' # ⛔️ TypeError: string indices must be integers result = my_str[my_index]

We tried using a string index but this is not allowed.

If you have an integer that is wrapped in a string, use the int() class to convert it.

main.py
my_str = 'hello' my_index = '1' # ✅ convert str to int result = my_str[int(my_index)] print(result) # 👉️ 'e'
We have to use an integer (e.g. my_str[2]) or a slice (e.g. my_str[0:2]) for string indices.

If you print the type of the value you are passing between the square brackets, it won't be an integer.

main.py
example = '1' print(type(example)) # 👉️ <class 'str'>

If you need to get a slice of a string, use a colon to separate the start and end indices.

main.py
my_str = 'hello world' # 👇️ from index 0 (inclusive) to 5 (exclusive) print(my_str[0:5]) # 👉️ 'hello' # 👇️ from index 6 (inclusive) to end print(my_str[6:]) # 👉️ 'world'

The first example shows how to get the first 5 characters from a string, and the second example - from character at index 6 onwards.

If you need to iterate over a string with an index, use the enumerate() function.

main.py
my_str = 'hello' for idx, char in enumerate(my_str): print(idx, char) # 👉️ 0 h, 1 e, 2 l, 3 l, 4 o

The idx variable stores the index of the current iteration and the char variable stores the corresponding character.

If you meant to declare a variable that stores key-value pairs, use a dictionary instead.

main.py
my_dict = {'name': 'Alice', 'age': 30} print(my_dict['name']) # 👉️ 'Alice' print(my_dict['age']) # 👉️ 30

If you need to iterate over a dictionary, use the items() method.

main.py
my_dict = {'name': 'Alice', 'age': 30} for key, value in my_dict.items(): print(key, value) # 👉️ name Alice, age 30

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

If you got the error when working with a JSON string, make sure to parse the JSON into a native Python object before accessing specific items.

main.py
import json my_json = json.dumps( ['apple', 'banana', 'kiwi'] ) print(type(my_json)) # 👉️ <class 'str'> # ✅ convert to native Python object my_list = json.loads(my_json) print(my_list[0]) # 👉️ 'apple' print(my_list[1]) # 👉️ 'banana' print(type(my_list)) # 👉️ <class 'list'>

The json.loads method parses a JSON string into a native Python object.

Conversely, the json.dumps method converts a Python object to a JSON formatted string.

You can use the enumerate() function if you need to access the index while iterating over a list.

main.py
my_list = ['a', 'b', 'c'] for idx, elem in enumerate(my_list): print(idx, elem) # 👉️ 0 a, 1 b, 2 c
The error "string indices must be integers" occurs when the type of the value between the square brackets is not an integer, nor is it a slice.

If you aren't sure what type of object a variable stores, use the type() class.

main.py
my_str = 'hello' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True my_dict = {'name': 'Alice', 'age': 30} print(type(my_dict)) # 👉️ <class 'dict'> print(isinstance(my_dict, dict)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Conclusion #

The Python "TypeError: string indices must be integers" occurs when we use a non-integer value to access a string at an index. To solve the error, make sure to use an integer, e.g. my_str[2] or a slice, e.g. my_str[0:3] when accessing a string at a specific index.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.