TypeError:字符串指数必须是整数
时间:2020-02-23 14:43:46 来源:igfitidea点击:
在本教程中,在Python我们会遇到 TypeError: String Indices Must be Integers
我们可以通过其索引访问字符串的字符。
每个索引指定字符的位置。
例如:假设我们要打印字符串的第3个元素 'theitroad' , 我们可以使用 str1[2]
。
str1 ="theitroad" print(str1[2])
如果你提供 string
或者 float
价值到指数,你会得到 TypeError: String Indices Must be Integers
例如:
str1 ="theitroad" print(str1['2'])
输出:
-------------------------------------------------------------------------- TypeError Traceback (most recent call last) in 1 str1 ="theitroad" ----> 2 print(str1['2']) TypeError: string indices must be integers
要解决此问题,我们需要通过 2
而不是字符串 '2' 你无法通过 float
也是字符串中的索引。
让我们在举例的帮助下看看。
str1 ="theitroad" print(str1[2.14])
输出:
-------------------------------------------------------------------------- TypeError Traceback (most recent call last) in 1 str1 ="theitroad" ----> 2 print(str1[2.14]) TypeError: string indices must be integers
要解决此问题,我们需要通过 2
而不是字符串 2.14
。