Are you facing the “TypeError: string indices must be integers” error when iterating over a string, list, or dictionary in Python?
In Python, we use indices to iterate over an iterable like a tuple, dictionary, list, or string. An index is the location of a specific value in any of the following data structures. And one of the properties of an index is that it should always be an integer. Others might face TypeErrors like string indices must be integers.
But before digging into that part of the topic, first, let’s discuss what TypeError is in Python.
Table of Contents
What is a TypeError in Python?
In Python, TypeError is one the most common exception that you will face, mainly in your early stages of Python. This error is raised when an invalid operation is performed with the object types.
Hence, it is familiar exception developers face in Python when the data type of objects is used invalidly. It represents an error when the operation cannot be performed in Python.
Moreover, the error string indices must be integers in Python that occur when you access the values of iterables like strings, tuples, and lists invalidly.
There could be different reasons behind the cause of TypeError in Python. Let’s discuss a few different scenarios in Python that raised the TypeError exception.
Example 1
Code
# String and int addition cause TypeError x ="Hello" y = 123 print(x+y)
Output
TypeError: can only concatenate str (not "int") to str
# Invalid use of Python Objects print(str) print(int) print(dict) print(list)
The above four statements throw TypeError: ‘str’ object is not callable
Code
# Iterating over a list items = ['Hello', 'Hi', 'Bye'] for i in items: print(items[i])
Output
TypeError: list indices must be integers or slices, not str
Example 2
Code
print(3/"x")
Output
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Code
print('2'+2)
Output
TypeError: can only concatenate str (not "int") to str
Code
lst = [1, 2] tpl = (4, 5) print(tpl+lst)
Output
TypeError: can only concatenate tuple (not "list") to tuple
Code
myInt = 100 myInt()
Output
TypeError: 'int' object is not callable
Code
string = "GuidingCode.com" print(string['G'])
Output
TypeError: string indices must be integers
All of the above scenarios throw a TypeError exception, and hundreds of cases could cause the TypeError exception in Python. And explaining all these scenarios in a single article would not be possible to do so. 🤔
Finally, we have understood TypeError in Python now; let’s discuss a scenario of TypeError and try to fix it.
What is the “TypeError: String Indices Must be Integers”?
By now, it’s clear that the “TypeError: string indices must be integers” error occurs in Python when accessing an iterable with an invalid index. Also, as mentioned before, an index is a location of a value in an iterable, and its data type should be an integer.
So long story short, to access values of the strings, lists, or tuples, you’ll need an index, but when you try to use an invalid index, you’ll get the “TypeError: string indices must be integers” error.
Let’s see a few examples that cause the TypeError string indices must be integers.
Code
# create a list of coding sites lst = ["GuidingCode","StackOverFlow","Delftstack","Quora"] # access the first site and print it print(lst['GuidingCode'])
Output
TypeError: list indices must be integers or slices, not str
Code
# create a tuple of countries tpl = ["Malaysia", "Pakistan","USA","UK","Turkey"] # access the first item of the tpl print(tpl['1'])
Output
TypeError: list indices must be integers or slices, not str
Code
# create a string string = "GuidingCode.com" # access the first value of the string print(string['1'])
Output
TypeError: string indices must be integers
As you can see, all the above are different scenarios, but each has the “TypeError: string indices must be integers.” And the reason is that if you can see where you are using an invalid index for each iterable to access data, the index should be an integer.
How to Fix the “TypeError: String Indices Must be Integers” Error in Python?
So far, we have discussed TypeError and the different scenarios that cause it. So now it’s time to fix the “TypeError: string indices must be integers” error in Python.
We understood that the error occurs when you use the indices of an iterable in an invalid manner. Additionally, we know the property of indices that it must be an integer, which means you cannot use any other data types, like string, boolean, etc., as an index. Hence, let’s use a valid index to access the values from an iterable
The index always starts with 0 to access the first element of an iterable. You have to use the starting index as 0 instead of 1.
Let’s see a few examples of the error and fix them.
Example of Iterating Over a String Input
Code
s = "GuidingCode.com" for i in s: print(s[i])
Output
TypeError: string indices must be integers
Look at the above example; we are trying to iterate over the string s to read the individual character of it using a for a loop. I’m saying to the Python compiler hey, compiler! Please print the value i in the s string at i position. And it raises the TypeError string indices that must be integers because, in the above case, the index is a string instead of an integer.
To fix this error, you need to tweak the index and provide an integer value instead of other data types.
Code
s = "GuidingCode.com" for i in s: print(i, end=" ")
Output
G u i d i n g C o d e . c o m
Great! It’s working perfectly!
Example of Accessing Individual Values of String Input
Let’s try to access individual values of the string s. The syntax is a pretty simple collection[index]:
Code
s = "GuidingCode.com" # print value at index 0 print(s[0]) # print value at index 6 print(s[6]) # print value at index 13 print(s[13])
Output
G g o Code # create a list of coding sites lst = ["GuidingCode","StackOverFlow","Delftstack","Quora"]
Code
# access the first site and print it print(lst[0])
Output
GuidingCode
Code
# create a string site = "GuidingCode.com" # access the 6th element of the string print(site[5])
Output
n
Example of Using Index as a Sublist
You can also use the index as a sublist, but the index range should be integer. For example, let’s print the first 11 values of the string site.
Code
# create a string site = "GuidingCode.com" # access the 6th element of the string print(site[0:11])
Output
GuidingCode
This code says to the Python compiler, Hey! Compiler, please print the values from locations 0 to 11 from the string site. Isn’t this cool? 😎
Example of Accessing Values From a Dictionary
Furthermore, when you try to access values from a dictionary using a string value, you might face the TypeError string indices must be integers.
Dictionary is a data structure that works in key-value pairs; every key has the corresponding value, and you can access the value using the specific key. Let’s see an example:
Code
dic = {"One": 1, "Two": 2, "Three" : 3} for i,j in dic.items(): print(f'The value of Key \'{i}\' is {j}')
Output
The value of Key' One' is 1 The value of Key 'Two' is 2 The value of Key' Three' is 3
This example has demonstrated the working of a dictionary in Python and how to traverse it using a look. But the point to remember here is we have used the proper index to access the keys and values.
On the other hand, if you try to traverse the same dictionary using an invalid index, it will raise TypeError string indices must be integers.
Code
for i in dic: print(i["One"])
Output
TypeError: string indices must be integers
Using Exception Handling to Fix the TypeError
To save your Python program from crashing down due to the TypeError, you should use exception handling techniques that give you options to customize the error messages, which helps in error understanding and detection. Let’s use try-catch exception handling blocks in our Python program.
Code
try: s = "GuidingCode.com" for i in s: print(s[i]) except TypeError: print("you have used indices in an invalid manner\nPlease fix it.") print("An error occurred, but the program isn't crashed")
Output
You have used indices in an invalid manner Please fix it An error occurred but the program isn't crashed
Exception handling is a powerful technique that helps customize the error message and saves your program from crashing. You can see the above 👆 code has demonstrated the concept the program has raised TypeError, but before crashing, it was handled by the except block.
Conclusion
To summarize the article on how to fix this “TypeError: String indices must be integers” error in Python, we have discussed what a TypeError is in Python and the different scenarios that cause the TypeError. We have also discussed how to fix the TypeError in traversing on an iterable like a string, list, dictionary, etc.
Let’s have a quick recap of the topics we have covered in this article.
- What is TypeError in Python?
- What are the different scenarios that cause TypeError in Python?
- How to fix TypeError string indices must be integers?
- What is a dictionary in Python, and how to traverse it?
Time to explore more 💻 can we access the keys and values of a dictionary using the loop index only?