Python 中 TypeError: string indices must be integers 错误
当我们使用非整数值访问索引处的字符串时,会出现 Python“TypeError: string indices must be integers”。 要解决错误,需要确保使用整数,例如 my_str[2]
或一切片,例如 my_str[0:3]
在访问特定索引处的字符串时。
下面是一个产生上述错误的示例
**my_str = 'hello'
# 👇️ this is also a string
my_index = '1'
# ⛔️ TypeError: string indices must be integers
result = my_str[my_index]**
我们尝试使用字符串索引,但这是不允许的。
如果我们有一个包含在字符串中的整数,请使用
int()
函数对其进行转换。
my_str = 'hello'
my_index = '1'
# ✅ convert str to int
result = my_str[int(my_index)]
print(result) # 👉️ 'e'
我们必须使用整数(例如
my_str[2]
)或切片(例如my_str[0:2]
)作为字符串索引。
如果打印在方括号之间传递的值的类型,则它不会是整数。
example = '1'
print(type(example)) # 👉️ <class 'str'>
如果我们需要获取字符串的一部分,请使用冒号分隔开始和结束索引。
my_str = 'hello world'
# 👇️ from index 0 (inclusive) to 5 (exclusive)
print(my_str[0:5]) # 👉️ 'hello'
# 👇️ from index 6 (inclusive) to end
print(my_str[6:]) # 👉️ 'world'
第一个示例展示了如何从字符串中获取前 5 个字符,第二个示例展示了如何从索引 6 处的字符开始。
如果需要遍历带有索引的字符串,请使用
enumerate()
函数。
my_str = 'hello'
for idx, char in enumerate(my_str):
print(idx, char) # 👉️ 0 h, 1 e, 2 l, 3 l, 4 o
idx
变量存储当前迭代的索引,char
变量存储相应的字符。
如果我们打算声明一个存储键值对的变量,请改用字典。
my_dict = {'name': 'Alice', 'age': 30}
print(my_dict['name']) # 👉️ 'Alice'
print(my_dict['age']) # 👉️ 30
如果需要遍历字典,请使用 items()
方法。
my_dict = {'name': 'Alice', 'age': 30}
for key, value in my_dict.items():
print(key, value) # 👉️ name Alice, age 30
dict.items
方法返回字典项((键,值)对)的新视图。
如果在使用 JSON 字符串时出现错误,请确保在访问特定项目之前将 JSON 解析为本机 Python 对象。
import json
my_json = json.dumps(
['apple', 'banana', 'kiwi']
)
print(type(my_json)) # 👉️ <class 'str'>
# ✅ convert to native Python object
my_list = json.loads(my_json)
print(my_list[0]) # 👉️ 'apple'
print(my_list[1]) # 👉️ 'banana'
print(type(my_list)) # 👉️ <class 'list'>
json.loads
方法将 JSON 字符串解析为本机 Python 对象。
相反,
json.dumps
方法将 Python 对象转换为 JSON 格式的字符串。
如果我们需要在遍历列表时访问索引,则可以使用 enumerate()
函数。
my_list = ['a', 'b', 'c']
for idx, elem in enumerate(my_list):
print(idx, elem) # 👉️ 0 a, 1 b, 2 c
当方括号之间的值的类型不是整数,也不是切片时,会出现“string indices must be integers”错误。
如果我们不确定变量存储的对象类型,请使用 type()
函数。
my_str = 'hello'
print(type(my_str)) # 👉️ <class 'str'>
print(isinstance(my_str, str)) # 👉️ True
my_dict = {'name': 'Alice', 'age': 30}
print(type(my_dict)) # 👉️ <class 'dict'>
print(isinstance(my_dict, dict)) # 👉️ True
type
类返回对象的类型。
如果传入的对象是传入类的实例或子类,则
isinstance
函数返回 True。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。