Python Error Message: string indices must be integers

If you are programming, you will inevitably get error messages. Unfortunately, they are part of programming, though you can learn to avoid them, you cannot avoid all of them all the time. This is particularly true when you are writing a large complex program. Fortunately, solutions exist for these problems.

What is this error?

The string indices must be integers error message is simply a case of using the wrong type of index value on a python string. In the Python programming language, a string value can be treated as an array where each array element is a character. Like an array, a python string has to use an integer index function or integer value in your user input Python code. You will get this message if you use a string value.

st = 'Do right!'
print (st['2nd'])

You will also get this message by using a float value as in this user input Python code example.

st = 'Do right!'
print (st[2.5])

In both cases, the index is not an integer value resulting in our string indices error message. This type of coding mistake is most likely to happen when using variables to set the indexing because you do not see the content of the integer index variable.

Why does it occur?

In many programming languages, Python included, a string is basically considered an array object consisting of characters. Like any array, the index of a string value has to be an index. If you try entering a value that is not an integer it will be producing an error message. It can also occur if you read your index from a file such as a json file that uses human-readable text, to store data. In such a case it is possible to load, an index as a character data without even knowing it.

How do I fix it?

Fixing the string indices must be integers error message output is quite simple. It is a matter of making sure that the index is an integer. Look at this code example, simply using an integer as the index.

st = 'Do right!'
print (st[2])

In cases where you have to read the index as a string, you can convert it to an integer.

st = 'Do right!'
print (st[int('2')])

You can also convert a float value to an integer by the same method.

st = 'Do right!'
print (st[int(2.5)])

All of these cases will work without producing an error message. The string indices must be integers error message is easy to understand and just as easy to fix. You can either simply make sure the index is an integer or convert another data type into an integer. In either case, it is easy to fix, and once you are aware of it, it is usually easy to avoid. The only exception would be when loading data in from a file.

Python Error Message: string indices must be integers

Leave a Reply

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

Scroll to top