Python (Help) TypeError: 'str' 对象不能被解释为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40445605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:33:38  来源:igfitidea点击:

(Help) TypeError: 'str' object cannot be interpreted as an integer

pythonpython-3.x

提问by AMVGod Z

    Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    get_odd_palindrome_at('racecar', 3)
  File "C:\Users\musar\Documents\University\Courses\Python\Assignment 2\palindromes.py", line 48, in get_odd_palindrome_at
    for i in range(string[index:]):
TypeError: 'str' object cannot be interpreted as an integer


I want to use the value index refers to but how do I do that?

我想使用引用的价值指数,但我该怎么做?

回答by vincent-lg

It seems from your error than the 'index' variable is a string, not an int. You could convert it using int().

从你的错误看来,'index' 变量是一个字符串,而不是一个整数。您可以使用 int() 转换它。

index = int(index)
for i in range(string[index:]):   

Now, string[index:] will also be an string. So you would need to convert that too:

现在, string[index:] 也将是一个字符串。所以你也需要转换它:

>>> string = "5"
>>> range(string)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got str.
>>> range(int(string))
[0, 1, 2, 3, 4]
>>>

That's assuming that string[index:] only contains a number. If that's not always the case, you can do something like:

那是假设 string[index:] 只包含一个数字。如果情况并非总是如此,您可以执行以下操作:

# 'index' contains only numbers
index = int(index)
number = string[index:]
if number.isdigit():
    number = int(number)
    for i in range(number):   

From the Wikipedia article on Python:

来自维基百科关于 Python 的文章

Python uses duck typing and has typed objects but untyped variable names. Type constraints are not checked at compile time; rather, operations on an object may fail, signifying that the given object is not of a suitable type. Despite being dynamically typed, Python is strongly typed, forbidding operations that are not well-defined (for example, adding a number to a string) rather than silently attempting to make sense of them.

Python 使用鸭子类型并具有类型化的对象但未类型化的变量名称。编译时不检查类型约束;相反,对对象的操作可能会失败,这表明给定的对象不是合适的类型。尽管是动态类型的,但 Python 是强类型的,禁止未明确定义的操作(例如,向字符串添加数字),而不是默默地尝试理解它们。

In this case, you try to pass a string to range(). This function waits for a number (a positive integer, as it is). That's why you need to convert your string to int. You could actually do a bit more of checking, depending on your needs. Python cares for types.

在这种情况下,您尝试将字符串传递给 range()。这个函数等待一个数字(一个正整数,因为它是)。这就是为什么您需要将字符串转换为 int 的原因。你实际上可以做更多的检查,这取决于你的需要。Python关心类型。

HTH,

哈,