TypeError: string indices must be integers in Python [Fixed]

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
4 min

banner

# 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.

main.py
my_str = 'hello' print(my_str[0]) # ๐Ÿ‘‰๏ธ 'h' print(my_str[1]) # ๐Ÿ‘‰๏ธ 'e print(my_str[0:2]) # ๐Ÿ‘‰๏ธ 'he'

use integer indices

# Use an integer or a slice for string indices

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'

use integer or slice for string indices

We used the int() class to convert the string to an integer to be able to access the original string at an index.

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(a_string) - 1.

# Getting a slice of a string

The error also occurs when you use string slicing incorrectly and separate the indices by a comma instead of a colon.

main.py
my_str = 'hello' # โ›”๏ธ TypeError: string indices must be integers, not 'tuple' new_str = my_str[0, 2]

separating indices by a comma instead of a colon

To solve the error, use a colon instead of a comma to separate the start and stop indices.

The syntax for string slicing is a_string[start:stop:step].

main.py
my_str = 'hello' new_str = my_str[0: 2] print(new_str) # ๐Ÿ‘‰๏ธ "he"

If your start and stop indices are wrapped in strings, convert them to integers.

main.py
start_index = '0' stop_index = '2' my_str = 'hello' new_str = my_str[int(start_index):int(stop_index)] print(new_str) # ๐Ÿ‘‰๏ธ 'he'

We used the int() class to convert both values to integers when slicing the string.

The syntax for string slicing is a_string[start:stop:step].

main.py
my_str = 'hello' print(my_str[0:2]) # ๐Ÿ‘‰๏ธ he print(my_str[1:4]) # ๐Ÿ‘‰๏ธ ell

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

If the start index is omitted, it is considered to be 0, if the stop index is omitted, the slice goes to the end of the string.

# Iterating over a string

If you need to iterate over a string, use a simple for loop.

main.py
my_str = 'abc' for char in my_str: print(char) # ๐Ÿ‘‰๏ธ a, b, c

iterating over string

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

main.py
my_str = 'abc' for idx, char in enumerate(my_str): print(idx, char) # ๐Ÿ‘‰๏ธ 0 a, 1 b, 2 c

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

# The input() function always returns a string

If you use the input() function to take input from the user, note that the function always returns a string.

main.py
my_str = 'hello' index = input('Enter an index: ') print(index) # ๐Ÿ‘‰๏ธ 0 print(type(index)) # ๐Ÿ‘‰๏ธ <class 'str'> # โ›”๏ธ TypeError: string indices must be integers, not 'str' print(my_str[index])

input returns string

Even if the user entered an integer, the input() function converts the value to a string and returns the result.

Instead, use the int() class to convert the string to an integer.

main.py
my_str = 'hello' # โœ… Convert to an integer index = int(input('Enter an index: ')) print(index) # ๐Ÿ‘‰๏ธ 0 print(type(index)) # ๐Ÿ‘‰๏ธ <class 'str'> print(my_str[index])

convert value to integer

We used the int() class to convert the value to an integer to be able to access the string at an index.

# Use a dictionary if you need to store key-value pairs

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

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 30} print(my_dict['name']) # ๐Ÿ‘‰๏ธ 'Bobby Hadz' print(my_dict['age']) # ๐Ÿ‘‰๏ธ 30

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

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 30} for key, value in my_dict.items(): print(key, value) # ๐Ÿ‘‰๏ธ name Bobby Hadz, age 30

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

# Make sure to parse your JSON

If you get 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.

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.

# Checking what type a variable stores

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.

Want to learn more about working with strings in Python? Check out these resources: Remove the last N characters from a String in Python,Get the first N characters of a String in Python.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev