(帮助)TypeError:“str”对象不能解释为整数

2024-04-16 06:13:15 发布

您现在位置:Python中文网/ 问答频道 /正文

    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

我想使用索引所指的值,但我该怎么做呢?


Tags: inmostgetlinecallatfilelast
1条回答
网友
1楼 · 发布于 2024-04-16 06:13:15

从您的错误来看,“index”变量似乎是字符串,而不是int。您可以使用int()转换它。

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

现在,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]
>>>

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

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

来自the Wikipedia article on 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.

在本例中,尝试将字符串传递给range()。此函数等待一个数字(正整数,原样)。这就是为什么你需要把字符串转换成int,你可以根据你的需要做更多的检查。Python关心类型。

HTH公司

相关问题 更多 >