To fix the TypeError: string indices must be integers error, make sure that you are “using an integer value for the index.”
This error typically occurs when “you attempt to access a value from an iterable using a string index rather than an integer index.”
Common reasons for this error
- Attempting to index a string with a non-integer: Strings are indexed with integers, representing the position of each character.
- Mistaking a string for a list or dictionary: If you mistakenly treat a string as if it were a list or a dictionary, you might try to access its elements with a string index, leading to this error.
- JSON or dictionary parsing issues: When working with JSON or dictionaries, it’s common to retrieve values using keys. If you accidentally treat a JSON-encoded string or a string value from a dictionary as a dictionary itself, you might attempt to use a string as an index.
Reproduce the error
Scenario 1: String index VS. integer index
main_string = "python"
index = "1"
print(main_string[index])
If you run the above code, you will get the TypeError.
TypeError: string indices must be integers
Scenario 2: String indices must be integers, not tuples
main_string = "python"
print(main_string[0, 8])
Output
TypeError: string indices must be integers
Scenario 3: Accessing values using string index instead of integer index
person = {
"Name": "Mahavir",
"Phone": "0",
"Address": "Swarg Lok"
}
for k in person:
print("Name:" + k["Name"])
print("Phone:" + k["Phone"])
print("Address:" + k["Address"])
Output
TypeError: string indices must be integers
How to fix the error?
Scenario 1: String index vs. integer index
You can use the built-in int() function to convert a non-integer index to an integer.
main_string = "python"
index = "1"
print(main_string[int(index)])
Output
y
See, it returns the second element of the string whose index is 1st because the index starts from 0 in Python.
However, this approach is imperfect and will only work if the index can be successfully converted to an integer.
If the index is not a valid integer, it will raise a ValueError instead. For example, if the index is “x” instead of “1” in the above code, it will raise a ValueError.
Scenario 2: String indices must be integers, not tuples
main_string = "python"
print(main_string[0:3])
Output
pyt
Scenario 3: Accessing values using string index instead of integer index
person = {
"Name": "Mahavir",
"Phone": "0",
"Address": "Swarg Lok"
}
print("Name:" + person["Name"])
print("Phone:" + person["Phone"])
print("Address:" + person["Address"])
Output
Name:Mahavir
Phone:0
Address:Swarg Lok
That’s it.
Further reading
TypeError: ‘int’ object is not subscriptable