In Python, there are a lot of iterable objects like lists, strings, etc. With that iterable object, we can access its item by using its index numbers. But sometimes you will get the error “Typeerror: string indices must be integers” in Python, so what is the reason? Let’s go into detail.
The reason for this error
There is a lot of situation that makes you into this error. If you access the items in a string through an index, you can do something like this :
Example :
aString = "This is a String" print(aString[0])
Output :
T
However, sometimes you will pass in the wrong type, not an integer, something like a string just like this:
aString = "This is a String" print(aString['0'])
The error will happen :
line 2, in <module>
print(aString['0'])
TypeError: string indices must be integers
Or while you are trying to use the slice. Example :
aString = "This is a String" print(aString[0:'3'])
Output :
line 2, in <module>
print(aString[0 : '4'])
TypeError: slice indices must be integers or None or have an __index__ method
Example :
aString = "This is a String" print(aString[0, 4])
Output
line 2, in <module>
print(anString[0 , 4])
TypeError: string indices must be integers
The computer will think that you are passing a tuple. It is wrong.
Solutions to TypeError: string indices must be integers in Python
Solution 1: Convert it into an integer
Example :
aString = "This is a String" print(aString[0:int('4')])
Output :
This
Solution 2: Check data type before pass it in
The solution for this error is quite simple. You need to make sure that you are passing an integer type. You can use the type()
function to check the type of thing you pass in.
Example :
aString = "This is a String" number = 5 print(type(number)) print(aString[number])
Output :
<class 'int'>
i
Summary
We hope you will enjoy our article about the TypeError: string indices must be integers in python. If you have any questions about this issue, please comment below, and we will respond as possible. Thank you for your reading!
Maybe you are interested:
- typeerror: takes 1 positional argument but 2 were given
- TypeError: unhashable type: ‘dict’
- TypeError: unhashable type: ‘dict’ in Python
- TypeError: unhashable type: ‘list’
Hello, guys! I hope that my knowledge in HTML, CSS, JavaScript, TypeScript, NodeJS, ReactJS, MongoDB, Python, MySQL, and npm computer languages may be of use to you. I’m Brent Johnson, a software developer.
Name of the university: HOU
Major: IT
Programming Languages: HTML, CSS, JavaScript, TypeScript, NodeJS, ReactJS, MongoDB, PyThon, MySQL, npm