Here, in this article, we are going to see the possible reasons and solutions for the error “TypeError: string indices must be integers” in python.
Before solving the problem let’s find out why did this error occurs.
A TypeError rose when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch. This exception may be raised by user code to indicate that an attempted operation on an object is not supported, and is not meant to be.
To understand the above lines, let’s take an example.
Let’s initialize a string in python:
example_string= 'The Crazy Programmer'
As python is dynamically typed you need not to define its data type.
Now we will be doing two operations on our string that will give us this error and will solve the error.
1. To fetch character from our string that is indexing
Syntax -> variable_name[index].
To understand the above let’s take our example.
example_string='The Crazy Programmer' print(example_string['a'])
When you run the above line, the interpreter will look for integer at the index but as we have passed the value as a string it will throw the error.
“TypeError: string indices must be integers”
The indexing operation requires an integer and we are passing a string.
Now take a look at the solution:
example_string='The Crazy Programmer' print(example_string[0])
Output
T
example_string='The Crazy Programmer' print(example_string[6])
Output:
a
As you see we get our output our problem is resolved.
2. To fetch a range of character from our string that is slicing
Syntax -> variable_name [start :end :step]
example_string='The Crazy Programmer' print(example_string[0,2])
Output:
TypeError: string indices must be integers
When you run the above line, the interpreter will look for integer at the start and end separated by colon (:) but as we have separated value using comma (,) it will throw the error “TypeError: string indices must be integers”.
example_string='The Crazy Programmer' print(example_string[0:3])
Output:
The
example_string='The Crazy Programmer' print(example_string[4:9])
Output:
Crazy
Conclusion
If an object is meant to support a given operation but has not yet provided an implementation, NotImplementedError is the proper exception to raise. Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError.