Skip to content

TypeError: String Indices Must Be Integers (Solved)

The string indices must be integers error occurs when trying to access string using something other than an integer.

TypeError: String indices must be integers

Take the following examples:

x[‘5’] x[2.5], x[‘u’] 
Will result in TypeErrors. 

However, using integers will generally solve this issue:

x[0], x[5], x[23]
Will work as normal.

The rest of this guide will make sure you understand what is happening, and go into more detail about the error.

First, we are going to check if you are in fact getting a “String indices must be integers” error. Then we are going to explain a couple of terms to give you a better idea of why the error is occurring in the first place. Last, we will try to solve the error.

What is the error

You are probably getting more or less the following feedback when you run your code:

Traceback (most recent call last):
File "C:\Users\username\Desktop\pythonfile.py", line 2, in <module>
print (x['0'])
TypeError: string indices must be integers

Your output does not have to be the exact same as the one above. But if it is close enough, then this is the right guide for you.

Terminology to understand before troubleshooting a String indices must be integers error

You might already be familiar with the following terms. If you are, then you can skip ahead to the solution.

String

Python has several data types. They include:

  • strings
  • integers
  • floats
  • complex
  • boolean
  • lists
  • tuples
  • range

Most of these are outside the scope of the error you are facing. The relevant ones at the moment are strings and integers.

Python strings are sequences of Unicode characters. Any combination of alphabetical characters and digits that can be interpreted by a human being are more often than not strings.

There is a good possibility the text you are reading right now on this website is a string.

Strings are enclosed inside double quotes or single quotes. Here are some  examples:

“My code has errors!”
“I love Python!”
“I am a programmer.”

Integer

Integers are whole numbers. They can either be positive or negative. Integers cannot have decimals.

Here are a couple of integer examples:

val = 5
negval = -222456238

Please note, decimals like 2.5 and 5.4 are not integers. They are another data type known as float values.

String indices

Python strings are indexed. In other words, every single character in a string is numbered starting from 0.

Here is an example:

x = “I am a programmer.” 
print (x[0]) #The answer will be “I”, which is the first letter and character in the string.
print (x[2]) #The answer will be “a”, which is the second letter and third character in the string. Python counts spaces as strings.

We call these references ([0], [1], [2], etc) indexes or indices. It is very important to remember this.
You might be wondering why “I” is indexed as [0] and not [1]. This is a quirk of most programming languages. The first item in a list or sequence is always labelled 0.

String indices must be integers

You now have an understanding of the three main terms associated with this error: strings, integers, and string indices. It is now time to find out why this error occurs.

Error type

Knowing the error type can help you diagnose the problem faster. All the information you need can be found in the error message most of the times.

The error will look something like this: “TypeError: string indices must be integers”.

TypeErrors belong to a group of errors known as exceptions. An exception is an error that disrupts the normal operations of a program.

A TypeError occurs when a programmer tries to mix data types that do not go together. For example, confusing strings and integers.

For your own general knowledge, the major error types in Python are:

  • syntax errors
  • logic errors
  • exceptions

Why am I getting a String indices must be integers error

Remember how we just demonstrated string characters are indexed? Do you also remember we went into how whole numbers are integers?

For instance, index [0] is an integer.

The “String indices must be integers” error occurs when you try to print any of the characters in the string with any other data type that is not an integer. In other words, this error occurs when you use an index that is not a number to refer to a character in a string.

Here are some examples of statements that will result in a “String indices must be integers” error:

x = “I am a programmer.”
print (x[‘I’]) #”I” is a string and not an integer.
print (x[‘0’]) #Python assumes 0 is a string, because it is inside quotation marks. 

The golden rule here is you cannot use a string to access another string.

Solution

Solving the “String indices must be integers” error is simple. Make sure you only use integers (whole numbers) to call string characters.

X[0] is fine. X[‘1’] x[6.5], or X[‘g’] will always result in a TypeError. 

There are times you might not know a character’s index. Use the Index method in such cases.

Here is an example of the Index method in action:

x = “I am a programmer”

y = x.index(“m”)

print (y) #The answer will be 3.

 

Please note, the Index method will only return the first occurrence of the character.

Looping through a dictionary

A dictionary  is a variable that allows us to store other variables inside it. A dictionary has at least one key, which is like a variable name for values in the dictionary. Consider the following code snippet:

Name = {
‘first’: ‘David’,
‘last’: ‘North’,
}

“first” and “last” are keys, with “David” and “North” being their respective values.

Type Errors also occur when you try to call a dictionary value using the dictionary key inside a loop. This is because both a dictionary key and dictionary values are strings. Like we already established, you cannot use a string to call another string.

Let us imagine we have the following dictionary:

person = {
'name': 'jon',
'surname': 'snow',
'hair': 'brown',
}

The following will result in an error:

for display in person:

print(f"{display['name']} {display['surname']} has {display['hair']} hair.") # the output will be “TypeError: string indices must be integers”. 

On the other hand, the following code will successfully execute:

print(f"{person['name']} {person['surname']} has {person['hair']} hair.") #Displays “jon snow has brown hair.” 

This works because we are not printing the string inside a loop.

Conclusion

We first checked to make sure you are indeed getting a “String indices must be integers” error. We then briefly explored python terms associated with this error. The last thing we looked into is the solution itself.

“String indices must be integers” is a common Python error. Solving it is as simple as making sure you are using numeric (integer) indexes / indices when referring to individual string characters. Never loop through a dictionary using its keys to access the dictionary’s values.

Comments

Latest

As an Amazon Associate we earn from qualifying purchases.