Typeerror string indices must be integers ошибка

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

Для этого мы пишем функцию, которая возвращает нам номер символа, стоящего сразу после пробела — 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

Вёрстка:

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

I’m playing with both learning Python and am trying to get GitHub issues into a readable form. Using the advice on How can I convert JSON to CSV?, I came up with this:

import json
import csv

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

f = open("issues.csv", "wb+")
csv_file = csv.writer(f)

csv_file.writerow(["gravatar_id", "position", "number", "votes", "created_at", "comments", "body", "title", "updated_at", "html_url", "user", "labels", "state"])

for item in data:
    csv_file.writerow([item["gravatar_id"], item["position"], item["number"], item["votes"], item["created_at"], item["comments"], item["body"], item["title"], item["updated_at"], item["html_url"], item["user"], item["labels"], item["state"]])

Where «issues.json» is the JSON file containing my GitHub issues. When I try to run that, I get

File "foo.py", line 14, in <module>
csv_file.writerow([item["gravatar_id"], item["position"], item["number"], item["votes"], item["created_at"], item["comments"], item["body"], item["title"], item["updated_at"], item["html_url"], item["user"], item["labels"], item["state"]])

TypeError: string indices must be integers

What am I missing here? Which are the «string indices»? I’m sure that once I get this working I’ll have more issues, but for now, I’d just love for this to work!

When I tweak the for statement to simply

for item in data:
    print item

what I get is … «issues» — so I’m doing something more basic wrong. Here’s a bit of my JSON content:

{"issues": [{"gravatar_id": "44230311a3dcd684b6c5f81bf2ec9f60", "position": 2.0, "number": 263, "votes": 0, "created_at": "2010/09/17 16:06:50 -0700", "comments": 11, "body": "Add missing paging (Older>>) links...

when I print data, it looks like it is getting munged really oddly:

{u'issues': [{u'body': u'Add missing paging (Older>>) lin...

На чтение 4 мин Просмотров 18.5к. Опубликовано 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: строковые индексы должны быть целыми числами». Мы видели, что такое строковые индексы? Также мы увидели, почему строковые индексы должны быть целыми числами. Мы объяснили этот тип ошибки с помощью всех примеров и дали код решения для ошибки. Все ошибки подробно объясняются с помощью примеров. Вы можете использовать любую из функций по вашему выбору и вашим требованиям в программе.

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

Typeerror: string indices must be integers – How to Fix in Python

In Python, there are certain iterable objects – lists, tuples, and strings – whose items or characters can be accessed using their index numbers.

For example, to access the first character in a string, you’d do something like this:

greet = "Hello World!"

print(greet[0])
# H

To access the value of the first character in the greet string above, we used its index number: greet[0].

But there are cases where you’ll get an error that says, «TypeError: string indices must be integers» when trying to access a character in a string.

In this article, you’ll see why this error occurs and how to fix it.

There are two common reasons why the «TypeError: string indices must be integers» error might be raised.

We’ll talk about these reasons and their solutions in two different sub-sections.

How to Fix the TypeError: string indices must be integers Error in Strings in Python

As we saw in last section, to access a character in a string, you use the character’s index.

We get the «TypeError: string indices must be integers» error when we try to access a character using its string value rather the index number.

Here’s an example to help you understand:

greet = "Hello World!"

print(greet["H"])
# TypeError: string indices must be integers

As you can see in the code above, we got an error saying TypeError: string indices must be integers.

This happened because we tried to access H using its value («H») instead of its index number.

That is, greet["H"] instead of greet[0]. That’s exactly how to fix it.

The solution to this is pretty simple:

  • Never use strings to access items/characters when working with iterable objects that require you to use index numbers (integers) when accessing items/characters.

How to Fix the TypeError: string indices must be integers Error When Slicing a String in Python

When you slice a string in Python, a range of characters from the string is returned based on given parameters (start and end parameters).

Here’s an example:

greet = "Hello World!"

print(greet[0:6])
# Hello 

In the code above, we provided two parameters – 0 and 6. This returns all the characters within index 0 and index 6.

We get the «TypeError: string indices must be integers» error when we use the slice syntax incorrectly.

Here’s an example to demonstrate that:

greet = "Hello World!"

print(greet[0,6])
# TypeError: string indices must be integers

The error in the code is very easy to miss because we used integers – but we still get an error. In cases like this, the error message may appear misleading.

We’re getting this error because we used the wrong syntax. In our example, we used a comma when separating the start and end parameters: [0,6]. This is why we got an error.

To fix this, you can change the comma to a colon.

When slicing strings in Python, you’re required to separate the start and end parameters using a colon – [0:6].

Summary

In this article, we talked about the «TypeError: string indices must be integers» error in Python.

This error happens when working with Python strings for two main reasons – using a string instead of an index number (integer) when accessing a character in a string, and using the wrong syntax when slicing strings in Python.

We saw examples that raised this error in two sub-sections and learned how to fix them.

Happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

The TypeError: string indices must be integers occurs when you try to access a character or a slice in a string using non-integer indices. In this tutorial, we will look at the common scenarios in which this error occurs and how we can fix it.

fix typeerror string indices must be integers in python

Understanding the TypeError: string indices must be integers error

Let’s look at some examples where we reproduce this error to better understand why this error occurs. Having clarity on why an error occurs is an essential step in understanding and ultimately fixing the error.

Here’s an example –

# create a string
s = "hello"
# using a non-integer index
s["e"]

Output:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[3], line 4
      2 s = "hello"
      3 # using a non-integer index
----> 4 s["e"]

TypeError: string indices must be integers

In the above code, we created a string and then tried to use the string “e” as an index inside the [] notation. We get a TypeError stating that string indices must be integers.

Strings are a kind of sequence in Python. Other common types of sequences are lists, tuples, etc. Sequences are indexed using integers starting from 0. This means that the first element in a sequence has an index of 0, the second element has an index of 1, and so on. Indexes are used to access individual elements in a sequence (for example an element in a list, a character in a string, etc.). You can also use indexes to slice a sequence into smaller parts.

In the context of a string, the integer index represents the index of a specific character. For example, the index 0 is the index of the first character.

The error message TypeError: string indices must be integers is quite helpful because it tells us that only integers should be used as indices in a string. And since a different type is expected for the index, we get a TypeError.

What if, you try to use float values as an index? For example, if you use the value 0.0 which is mathematically equal to 0, will you still get the error? Let’s find out.

# create a string
s = "hello"
# using a float value as index
s[0.0]

Output:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Cell In[4], line 4
      2 s = "hello"
      3 # using a float value as index
----> 4 s[0.0]

TypeError: string indices must be integers

We still get the error. This shows us that only integer values are applicable as index values in Python.

Fixing the Error

Generally to fix a TypeError in Python, you have to use a value that is of the required type in the given code. In our case, it would be using an integer as an index value in a string.

For example, let’s fix the error in the above code where we’re using a float value as an index.

# create a string
s = "hello"
# using int value as index
s[int(0.0)]

Output:

'h'

Here, we first converted the float value 0.0 to an integer using the int() method and then used that integer value as the index to get the character 'h'.

Here’s a quick summary of steps that you can take to fix this error –

  1. Check the code where the error occurred and identify the line that caused the error.
  2. Make sure that you are using an integer value as an index when accessing a string. For example, if you have a string s and you want to access the first character, you should use s[0] instead of s['0'].
  3. If you are using a variable as an index, make sure that the variable is an integer. You can use the type() function to check the type of a variable.
  4. If you are still getting the error, check if you are trying to access a string using a float value as an index. In Python, you cannot use a float value as an index for a string.
  5. If none of the above steps work, try to print the value of the index variable before using it to access the string. This will help you identify any issues with the value of the index variable.

Once you have identified and fixed the issue, you should be able to run your code without getting the “TypeError: string indices must be integers” error.

Conclusion

The TypeError: string indices must be integers error occurs when you try to access a string using a non-integer value. This error can be fixed by checking the type of the index value and converting it to an integer if necessary.

You might also be interested in –

  • How to Fix – SyntaxError can’t assign to literal
  • How to Fix – SyntaxError can’t assign to operator
  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

  • Typeerror str object cannot be interpreted as an integer python ошибка
  • Typeerror object of type nonetype has no len ошибка
  • Typeerror nonetype object is not subscriptable python ошибка
  • Typeerror list indices must be integers or slices not str ошибка
  • Typeerror int object is not callable ошибка