Last updated: Apr 8, 2024
Reading timeยท4 min
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.
Here is an example of how the error occurs.
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.
my_str = 'hello' print(my_str[0]) # ๐๏ธ 'h' print(my_str[1]) # ๐๏ธ 'e print(my_str[0:2]) # ๐๏ธ 'he'
If you have an integer that is wrapped in a string, use the int() class to convert it.
my_str = 'hello' my_index = '1' # โ convert str to int result = my_str[int(my_index)] print(result) # ๐๏ธ 'e'
We used the int()
class to convert the string to an integer to be able to
access the original string at an index.
0
, and the last character has an index of -1
or len(a_string) - 1
.The error also occurs when you use string slicing incorrectly and separate the indices by a comma instead of a colon.
my_str = 'hello' # โ๏ธ TypeError: string indices must be integers, not 'tuple' new_str = my_str[0, 2]
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]
.
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.
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]
.
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.
If you need to iterate over a string, use a simple for loop.
my_str = 'abc' for char in my_str: print(char) # ๐๏ธ a, b, c
If you need to iterate over a string with an index, use the enumerate()
function.
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.
If you use the input()
function to take input from the user, note that the
function always returns a string.
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])
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.
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])
We used the int()
class to convert the value to an integer to be able to
access the string at an index.
If you meant to declare a variable that stores key-value pairs, use a dictionary instead.
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.
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).
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.
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.
If you aren't sure what type of object a variable stores, use the type()
class.
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.
You can learn more about the related topics by checking out the following tutorials: