Home Python How to avoid String indices must be integers error in Python

How to avoid String indices must be integers error in Python

This article will cover the core reasons for the TypeError: string indices must be integers mistakes in Python and a few instances. We believe that understanding why this error arises is critical because the better you understand the issue, the better you will avoid it.

Iterable objects are accessed in Python by using numeric values. An error will be thrown if we try to access the iterable object with a string value. “TypeError: string indices must be integers,” says the error message.

An Iterable is a set of elements that may be retrieved in a specific order. Numbers are used to index iterable objects in Python. An error will be thrown if you try to access an iterable object using a string or a float as the index.

Each character in a string has its index. The latter indicates the position of each character in the string. An attempt to access a position within a string using an index that is not an integer result in a TypeError: string indices must be integers. For example, for the indexes in str[“me”] and str[2.1], a TypeError exception is thrown since these aren’t integers. It means that you must use an integer value when accessing an iterable object like a string or float value.

What are string indices, and how do you use them?

Strings are character data that are arranged in a specific order. By directly using numeric values, string indices are used to access individual characters from a string. The string indexes begin with 0, indicating that the first character in the string is at index 0 and so on.

Integers are required for string indices

When we view iterable objects in Python, they are indexed with numbers. An error is given if we try to access the iterable object with the help of a string. “TypeError: string indices must be integers,” says the error message.

All of the characters in the strings have their unique index. The index specifies where each character in the string is located. However, all of the indexes must be integers because we can’t remember the position using a character, float value, or anything else.

This tutorial includes several code samples as well as possible solutions to the problem.

Using the float value of indices

We’ll use input_string to represent an input string in this example. Then, using the float value as their index, try to read the string. After that, we’ll look at the results. Finally, let’s look at an example to comprehend the notion better.

#input string
input_string = "codeunderscored"
 
p = input_string[1.5]
print(p)
Using the float value of indices
Using the float value of indices

To begin, we’ve set input_string = “codeunderscored” as an input string.
Then we created a variable p, into which we passed the index value as a float in the string’s range.
The index range of a string starts at 0 and ends at the length of the string, which is len(input_string -1).
Finally, the result has been printed.
As a result, you’ll notice “TypeError: string indices must be integers,” indicating you can’t use the character to access the string index.


The solution for the above-discussed code is as follows.

input_string = "codeunderscored"
 
p = input_string[1]
print(p)
solution to using the float value of indices
solution to using the float value of indices

Convert string indices to Integers

In Python, a String is a collection of characters. The index position of each character can be used to access it. Using anything other than an integer to index a string will result in an error. Error: String Indices Must Be Integers Consider the following scenario:

variable_holder = "codeunderscored solution"

print(variable_holder['solution']) # do not try this

print(variable_holder[1]) # how to go about it
Convert string indices to Integers
Convert string indices to Integers

Look at line 1. A string should be indexed with an integer but the code in line 1 above indexes with a string rather than an integer. Because Python doesn’t know how to execute this statement, it throws an error rather than proceeding with the execution.

You’ll run into this issue in most circumstances because you presume a variable is a dictionary when it’s a String.

Because Python is not a highly typed language, variables do not have a fixed type associated with them; this issue is relatively prevalent.

Example of a Dictionary

This issue appears to be simple, yet it may not be that evident when working with dictionaries.

Let’s look at some code that will cause our error:

students_dict = {
    'year': "2020",	
    'name': "tom",
    'age': 18
}

for item in students_dict:
    print(item['age'])
string indices must be integers in dictionaries
string indices must be integers in dictionaries

The goal of this code snippet is to print out all of the values in the dictionary. So what is the reason for the error? In line 2, the age variable is a String, not a dictionary.

Because you are attempting to access values from a dictionary using string indices rather than integers, TypeError: string indices must be integers has occurred.

If you’re looking for anything in a dictionary, make sure you’re looking for the dictionary itself, not a key in the dictionary. In the dictionary, the value of the item is always a key. It’s not a word that exists in the dictionary. Let’s see how we can use the item in a dictionary example:

students_dict = {
    'year': "2020",	
    'name': "tom",
    'age': 18
}

for item in students_dict:
    print(item)
look for the dictionary instead of key
look for the dictionary instead of key

The method must be called to loop over the method.values() as follows.

students_dict = {
    'year': "2020",	
    'name': "tom",
    'age': 18
}

for item in students_dict.values():
    print(item)
looping over values in a dictionary
looping over values in a dictionary

To grasp this, it’s important to note that when utilizing a dictionary in a for loop, the code will loop over the dictionary keys rather than the values by default.

Using Json as an Example

When working with JSON, the “TypeError: string indices must be integers” problem can also occur. For instance, assume we have a file containing students’ information, all saved in JSON format. Also, we’d like to build some code that returns the total number of employees over 15. The following is a sample of code:

# students.json
{"students_json":
  [
    { "academic_year": "3", "name": "Tom Ann", "age": 14},
    { "academic_year": "1", "name": "Samwel Brown", "age": 18},
    { "academic_year": "4", "name": "Keen Moses", "age": 12},
    { "academic_year": "2", "name": "Jane Smith", "age": 16
  ]
}
import json

f=open('students.json')
data = json.load(f)
f.close()

students_above_15s = 0
for students_json in data:
    if students_json["age"]>15:
        student_above_15s+=1

print( student_above_15s)
string indices must be integers in json
string indices must be integers in json

We get an error after running the code above. Why? Line 9 is the source of the issue. We think the students variable is a dictionary, but it’s a string with the value “students”.

As a result, the approach is to avoid trying to access a field on a String. And instead, use the dictionary. To correct the following code snippet, replace line 8 with for employee in data[‘students’], as seen below:

import json

f=open('students.json')
data = json.load(f)
f.close()

students_above_15s = 0
for student in data['students_json']:
    if student["age"]>15:
        students_above_15s+=1
        
print(students_above_15s)
solution to string indices must be integers in json
solution to string indices must be integers in json

Slice Notation string[x:y]

Python offers slice notation for every sequential data type, such as lists, strings, tuples, bytes, bytearrays, and ranges. However, while using slice notation on strings, a TypeError: string indices must be integers error can occur, indicating that the indices must be integers, even though they are apparent. Let’s consider the following example.

str = "Codeunderscored testing slice notation!"
str[0,4]
string indices must be integers in slice notation
string indices must be integers in slice notation

Python will evaluate something like a tuple with just a comma “,”. To correctly separate the two integers, you must replace the comma “,” with a colon “:”

str = "Codeunderscored testing slice notation!"
str[0:8]
solution to string indices must be integers in slice notation

Conclusion

To summarize, we’ve looked at a few circumstances in which you might encounter the “TypeError: string indices must be integers” error, as well as how to avoid it by only using integer indices.

This error message, like many others in Python, shows us exactly what we’ve done wrong. This error occurs when a value from an iterable is accessed using a string index rather than an integer index.

Iterables, such as strings and dictionaries, are indexed from 0 to 1.

Integers must be used for string indices. It means that you must use a number value when accessing an iterable object like a string. If you’re looking for anything in a dictionary, make sure you’re looking for the dictionary itself, not a key in the dictionary.
We hope you enjoyed this post and have a better understanding of this problem so you can avoid it when developing.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More