String indices must be integers python ошибка

Что это значит: интерпретатор говорит нам, что обращаться к содержимому строку через индекс (порядковый номер символа в строке) можно только с помощью целых чисел.

Ситуация: мы пишем программу, которая будет работать как словарь. Нам нужно отсортировать по алфавиту не слова, а словосочетания. Например, если у нас есть термины «Большой Каньон (США)» и «Большой Взрыв (Вселенная)». Первые слова одинаковые, значит, порядок будет зависеть от вторых слов. Получается, что сначала должен идти «Большой Взрыв», а потом «Большой Каньон», потому что «В» идёт в алфавите раньше, чем «К». 

Для этого мы пишем функцию, которая возвращает нам номер символа, стоящего сразу после пробела — whatNext(), а потом используем её, чтобы получить букву из строки:

def whatNext():
  # какой-то код, где переменная ind отвечает за номер символа
  return ind

# дальше идёт код нашей основной программы
# доходим до момента, когда нужно получить символ из строки phrase
# вызываем функцию и сохраняем то, что она вернула, в отдельную переменную
symbolIndex = whatNext()
# используем эту переменную, чтобы получить доступ к символу
symbol = phrase[symbolIndex]

Но после запуска компьютер выдаёт ошибку:

❌ TypeError: string indices must be integers

Что это значит: интерпретатор говорит нам, что обращаться к содержимому строку через индекс (порядковый номер символа в строке) можно только с помощью целых чисел. 

Когда встречается: когда вместо целого числа интерпретатор видит не его, а что-то другое — символ, другую строку, дробное число, объект или что-то ещё. Это единственная причина, по которой возникает такая ошибка.

Что делать с ошибкой TypeError: string indices must be integers

Раз мы знаем единственную причину, то решение очевидное: нужно проверить, что именно мы отправляем в качестве индекса. Судя по всему, проблема в нашей функции whatNext(), которая возвращает не целое число, а что-то иное. Сейчас мы не знаем, что именно, потому что мы не знаем, как работает whatNext().

Можно предположить, что в функции whatNext() происходили какие-то вычисления, которые возвращали не целое, а дробное число. При этом само число могло быть целым (например, 12), просто его зачем-то приводили к десятичной дроби (12,00). 

Другой вариант — функция возвращала не число, а строку с числом внутри, кортеж с одним числом, объект с числом. Для нас, людей, это всё ещё целое число, но для Python это другой тип данных. 

Чтобы это исправить, нужно зайти внутрь функции и перепроверить, что она возвращает.

Вот пара примеров, которые могут возникнуть во время работы:

Что означает ошибка TypeError: string indices must be integers

Что означает ошибка TypeError: string indices must be integers

Что означает ошибка TypeError: string indices must be integers

Но если поставить в индекс целое число — всё сработает, и мы получим символ, который стоит на этом месте в строке. На всякий случай напомним, что нумерация символов в Python идёт с нуля:

Что означает ошибка TypeError: string indices must be integers

Вёрстка:

Кирилл Климентьев

На чтение 4 мин Просмотров 14.9к. Опубликовано 30.04.2021

В этой статье мы рассмотрим из-за чего возникает ошибка TypeError: String Indices Must be Integers и как ее исправить в Python.

Содержание

  1. Введение
  2. Что такое строковые индексы?
  3. Индексы строки должны быть целыми числами
  4. Примеры, демонстрирующие ошибку
  5. Использование индексов в виде строки
  6. Использование индексов в виде числа с плавающей запятой
  7. Решение для строковых индексов
  8. Заключение

Введение

В Python мы уже обсудили множество концепций и преобразований. В этом руководстве обсудим концепцию строковых индексов, которые должны быть всегда целыми числами. Как знаем в Python, доступ к итеративным объектам осуществляется с помощью числовых значений. Если мы попытаемся получить доступ к итерируемому объекту, используя строковое значение, будет возвращена ошибка. Эта ошибка будет выглядеть как TypeError: String Indices Must be Integers.

Что такое строковые индексы?

Строки — это упорядоченные последовательности символьных данных. Строковые индексы используются для доступа к отдельному символу из строки путем непосредственного использования числовых значений. Индекс строки начинается с 0, то есть первый символ строки имеет индекс 0 и так далее.

Индексы строки должны быть целыми числами

В python, когда мы видим какие-либо итерируемые объекты, они индексируются с помощью чисел. Если мы попытаемся получить доступ к итерируемому объекту с помощью строки, возвращается ошибка. Сообщение об ошибке — «TypeError: строковые индексы должны быть целыми числами».

Все символы, присутствующие в строках, имеют свой уникальный индекс. Индекс используется для указания позиции каждого символа в строке. Но все индексы должны быть целыми числами, поскольку мы не можем запомнить позицию с помощью символа, значения с плавающей запятой и так далее.

Примеры, демонстрирующие ошибку

Здесь мы обсудим все примеры, которые покажут вам ошибку в вашей программе, поскольку строковые индексы должны быть целыми числами:

Использование индексов в виде строки

В этом примере будем использовать строку в переменной line. Затем мы попытаемся получить доступ к конкретному индексу строки с помощью строкового символа в качестве индекса, а затем посмотрим результат. 

Давайте посмотрим на пример для детального понимания концепции.

line = "Тестовая строка"

string = line["е"]
print(string)

Вывод программы:

Traceback (most recent call last):
  File "D:ProjectTESTp.py", line 3, in <module>
    string = line["е"]
TypeError: string indices must be integers

Объяснение:

  • Мы использовали входную строку в переменной line
  • Затем мы взяли переменную string, в которую мы передали значение индекса в виде строкового символа.
  • Наконец, мы распечатали результат.
  • Следовательно, вы можете увидеть ошибку TypeError: String Indices Must be Integers, что означает, что вы не можете получить доступ к строковому индексу с помощью символа.

Использование индексов в виде числа с плавающей запятой

В этом примере мы возьмем входную строку. А затем попробуйте получить доступ к строке с помощью значения с плавающей запятой в качестве их индекса. Затем мы увидим результат. 

Давайте посмотрим на пример для детального понимания концепции.

line = "Тестовая строка"

string = line[1.6]
print(string)

Вывод программы:

Traceback (most recent call last):
  File "D:ProjectTESTp.py", line 3, in <module>
    string = line[1.6]
TypeError: string indices must be integers

Объяснение:

  • Во-первых, мы взяли входную строку.
  • Затем мы взяли переменную string, в которую мы передали значение индекса как число с плавающей запятой в диапазоне строки.
  • Наконец, мы распечатали результат.
  • Следовательно, вы можете увидеть «TypeError: строковые индексы должны быть целыми числами», что означает, что вы не можете получить доступ к строковому индексу с помощью числа с плавающей запятой

Решение для строковых индексов

Единственное решение для этого типа ошибки: «Строковые индексы должны быть целыми числами» — это передать значение индекса как целочисленное значение. Поскольку доступ к итерируемому объекту можно получить только с помощью целочисленного значения. Давайте посмотрим на пример для детального понимания концепции.

line = "Тестовая строка"

string = line[3]
print(string)

Вывод программы:

Объяснение:

  • Во-первых, мы взяли входную строку.
  • Затем мы взяли переменную, в которую мы передали значение индекса как целое число в диапазоне строки.
  • Наконец, мы распечатали результат.
  • Следовательно, вы можете увидеть вывод буквы «т», поскольку 3-й символ строки — «т».

Заключение

В этом руководстве мы узнали о концепции «TypeError: строковые индексы должны быть целыми числами». Мы видели, что такое строковые индексы? Также мы увидели, почему строковые индексы должны быть целыми числами. Мы объяснили этот тип ошибки с помощью всех примеров и дали код решения для ошибки. Все ошибки подробно объясняются с помощью примеров. Вы можете использовать любую из функций по вашему выбору и вашим требованиям в программе.

Однако, если у вас есть какие-либо сомнения или вопросы, дайте мне знать в разделе комментариев ниже. Я постараюсь помочь вам как можно скорее.

Posted by Marta on May 2, 2021 Viewed 13939 times

Card image cap

In this article, I will explain the main reason why you will face the TypeError: string indices must be integers error in Python along with a few different examples. I think it is essential to understand why this error occurs, since the better you understand the error, the better your ability to avoid it.

This tutorial contains some code examples and possible ways to fix the error.

String Indices must be Integers

A String in Python is a sequence of characters. Each of this character can be accessed using its index position. Using anything else but an integer to index a string will raise a String Indices must be Integers error . For example:

variable1 = "Hello Code Club"

print(variable1[0]) #Correct

print(variable1['Hello'] # ERROR

Output:

H

Traceback (most recent call last):
  File  line 5, in <module>
    print(variable1['Hello'])  # Error
TypeError: string indices must be integers

Check out line 5. A String should be indexed using an integer, but instead, the code in line 5 is indexing using not an integer but a string. Python doesn’t know how to execute this statement, and therefore it throws an error because it can continue with the execution.

In most cases you will face this problem because you assume that a given variable is a dictionary, but it is a String.

This error is very common because Python is not a strongly type language, in other words, variables don’t have a fixed type associated to them.

Dictionary Example

This error looks straightforward; however, when we are working with dictionaries, it might not be as obvious. Let’s see a code snippet that will raise our error:

variable1 = {
    'name': "Luke",
    'age': 347
}

for item in variable1:
    print(item['name'])

Output:

Traceback (most recent call last):
  File line 7, in <module>
    print(item['name'])
TypeError: string indices must be integers

This code snippet aims to print out all values inside the dictionary. Why is it raising an error? The item variable in line 7 is a String, not a dictionary.

To understand this, it is essential to point out when using a dictionary in a for loop, by default, the code will loop over the dictionary keys, not over the values. See the example below:

variable1 = {
    'name': "Luke",
    'age': 347
}
for item in variable1:
    print(item)

Output:

To loop over the values, we need to called the method .values():

variable1 = { 'name': "Luke", 'age': 347}

for item in variable1.values():
    print(item)

Output:

Working with Json Example

Another example where the “TypeError: string indices must be integers” error occur is when working with JSON. Let’s imagine that we have a file containing employees information, all saved in JSON format in a file. And we want to write a piece of code that returns the numbers of employees over 30. See below the code snippet:

employees.json

{"employees":
  [
    { "name": "Luke", "age": 21},
    { "name": "Marta", "age": 32},
    { "name": "Mike", "age": 45},
    { "name": "Jane", "age": 22}
  ]
}
import json

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

employee_above_30s = 0
for employee in data:
    if employee["age"]>30:
        employee_above_30s+=1

print(employee_above_30s)

After running the above code, we get an error. Why? The problem is in line 9. We are assuming the employee variable is a dictionary but it’s actually a string that contains the value “employees”, which is .

Therefore the solution is avoiding trying to access a field on a String, and use the dictionary instead. The easiest way to fix the above code snippet is replacing line 8 by for employee in data['employees'], as below:

employee_above_30s = 0
for employee in data['employees']:
    if employee["age"]>30:
        employee_above_30s+=1

The employee is now a dictionary instead of a String.

Knowledge Quiz

Here is a chance to check how much you learned. See below a few quiz questions that will help you to confirm and reinforce your understanding. Find the solutions at the bottom of this article:

  1. What would this program output?
variable = "Hello"
print(variable["1"])

A) H

B) e

C) string indices must be integers error

Conclusion

To summarise, we have seen a few scenarios where you could face the “TypeError: string indices must be integers” error and how you can fix it by making sure you only use string indices on dictionaries.

I hope you enjoy this article, and understand this issue better to avoid it when you are programming.

Thank you so much for reading and supporting this blog!

Happy Coding!

Solution

1.C

More Interesting Articles

youtube comment bot
how to make a website like youtube
rock paper scissors java

String indices must be integers. This means that when obtaining an iterable object like a string, you must do it using a numerical value.

What are string indices?

String indices allow you to directly access individual characters in a string using a numeric value.

String indexing is zero-based, which means the first character in the string has an index of 0, the next character has 1, and so on.

String indexing in Python

To access a character of a string, reference it by its index numbers using the square brackets([ ]).

data = "EnolaHolmes2"
print(data[5])

Output

H

We accessed the character “H” from a string “EnolaHolmes2” using string indexing.

What is TypeError in Python?

TypeError in Python is an exception when the data type of an object in operation is inappropriate.

Why does TypeError occur?

The TypeError occurs because an operation is performed on an object of an incorrect type or is not supported.

After reviewing my entire codebase, I discovered the following reason that caused the error.

Typeerror: string indices must be integers error in Python occurs when we are attempting to access a value from an iterable using a string index rather than an integer index.

The iterable objects are indexed using numbers. Therefore, an error will be returned when you try to obtain an iterable object using a string value.

See the following example of code.

main_string = "metaverse"
index = "1"

print(main_string[index])

If you run the above code, you will get the TypeError.

TypeError: string indices must be integers

How to fix TypeError: String indices must be integers

Following is the answer that I came up with after carefully reviewing my codebase and performing a lot of trial-and-error approaches with the code.

To fix TypeError: string indices must be integers error, ensure you use an integer as the index when accessing a character in a string.

The built-in int() function converts a non-integer index to an integer.

main_string = "metaverse"
index = "1"

print(main_string[int(index)])

Output

e

See, it returns the second element of the string whose index is 1st because the index starts from 0 in Python.

We successfully solved TypeError: string indices must be integers error by converting an index to an integer using the int() function.

However, this approach is imperfect and will only work if the index can be successfully converted to an integer.

If the index is not a valid integer, it will raise a ValueError instead.

For example, if the index is “x” instead of “1” in the above code, it will raise a ValueError.

main_string = "metaverse"
index = "x"

print(main_string[int(index)])

Output

ValueError: invalid literal for int() with base 10: 'x'

Use the int() function approach when the index is convertible to int.

Tips and best practices for avoiding the “TypeError: String Indices must be Integers” error in the future

  1. Use integer indices when accessing elements of a string.
  2. Use the isinstance() function to check the variable type before using it as a string index.
  3. While iterating a for loop, use the loop variable as an integer index.
  4. If you are working with string indices stored as strings, convert them to integers using the int() function before using them as indices.

FAQs

What common mistakes can cause the “TypeError: String Indices must be Integers” error?

  1. Using a variable that is not an integer as a string index.
  2. Confusing string indices with string methods.
  3. Use a for loop variable that is not an integer as a string index.
  4. Using string indices stored as strings without converting them to integers first.

How can I avoid the “TypeError: String Indices must be Integers” error in the future?

  1. Use integer indices when accessing elements of a string.
  2. Use the isinstance() function that checks the variable type before using it as a string index.
  3. When storing string indices as strings, convert them to integers before using them as indices.

Conclusion

The string indices must be integer error occurs when accessing a string element using an invalid data type index instead of an int type index.

Ensure you use an integer as the index when accessing a character in a string to fix the TypeError.

Further reading

TypeError: ‘int’ object is not subscriptable

TypeError: bad operand type for unary +: ‘str’

TypeError: can only concatenate str not int to str

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.

In Python, iterable objects are indexed using numbers. When you try to access an iterable object using a string value, an error will be returned. This error will look something like “TypeError: string indices must be integers”.

In this guide, we’re going to discuss what this error means and why it is raised. We’ll walk through an example code snippet with this error and a solution to help you gain further context into how you can solve this type of error.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Let’s get started!

The Problem: typeerror: string indices must be integers

We have a TypeError on our hands. That means that we’re trying to perform an operation on a value whose type is not compatible with that operation. Let’s look at our error message:

typeerror: string indices must be integers

Like many Python error messages, this one tells us exactly what mistake we have made. This error indicates that we are trying to access a value from an iterable using a string index rather than an integer index.

Iterables, like strings and dictionaries, are indexed starting from the number 0. Consider the following list:

keyboard = ["Apex Pro", "Apple Magic Keyboard"];

This is a list of strings. To access the first item in this list, we need to reference it by its index value:

This will return a keyboard name: “Apex Pro”. We could not access this list item using a string. Otherwise, an error would be returned.

An Example Scenario

Let’s create a dictionary called “steel_series” which contains information on a keyboard:

steel_series = {
	"name": "Apex Pro",
	"manufacturer": "SteelSeries",
	"oled_display": True
}

We’re going to iterate over all the values in this dictionary and print them to the console.

for k in steel_series:
	print("Name: " + k["name"])
	print("Manufacturer: " + k["manufacturer"])
	print("OLED Display: " + str(k["oled_display"]))

This code uses a for loop to iterate through every item in our “keyboard” object. Now, let’s try to run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
	print("Name: " + k["name"])
TypeError: string indices must be integers

An error is present, as we expected. This error has been caused because we are trying to access values from our dictionary using string indices instead of integers.

The Solution

The problem in our code is that we’re iterating over each key in the “steel_series” dictionary.

The value of “k” is always a key in the dictionary. It’s not a record in our dictionary. Let’s try to print out “k” in our dictionary:

for k in steel_series:
	print(k)

Our code returns:

name
manufacturer
oled_display

We cannot use “k” to access values in our dictionary. k[“name”] is equal to the value of “name” inside “k”, which is “name”. This does not make sense to Python. You cannot access a value in a string using another string.

To solve this problem, we should reference our dictionary instead of “k”. We can access items in our dictionary using a string. This is because dictionary keys can be strings.

We don’t need to use a for loop to print out each value:

print("Name: " + steel_series["name"])
print("Manufacturer: " + steel_series["manufacturer"])
print("OLED Display: " + str(steel_series["oled_display"]))

Let’s run our new code:

Name: Apex Pro
Manufacturer: SteelSeries
OLED Display: True

Our code successfully prints out each value in our list. This is because we’re no longer trying to access our dictionary using the string value in an iterator (“k”).

Conclusion

String indices must be integers. This means that when you’re accessing an iterable object like a string, you must do it using a numerical value. If you are accessing items from a dictionary, make sure that you are accessing the dictionary itself and not a key in the dictionary.

Now you’re ready to solve the Python typeerror: string indices must be integers error like a pro!

Понравилась статья? Поделить с друзьями:
  • String error 102 hikvision
  • String descriptor 0 read error 71
  • Strict nat destiny 2 как исправить pc
  • Stopped upon error after linx
  • Stress web fatal error in unknown on line 0