How To Solve TypeError: String Indices Must Be Integers In Python

typeerror: string indices must be integers in python

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:

Leave a Reply

Your email address will not be published. Required fields are marked *