7.3 并且想知道为什么在下面的示例中字符串“racecar”被视为 int 类型。 在此先感谢您的帮助
>>> s = "racecar"
>>> for i in len(s):
print(s[i])
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
for i in len(s):
TypeError: 'int' object is not iterable
最佳答案
因为您需要使用 range(len(s))
来获取要迭代的整数列表(或 Python 2.x 中的 xrange
)。
或者,您可以使用enumerate()
:
for i, val in enumerate(s):
print(i)
print(val) # equivalent to s[i]
或者一开始就不要使用索引:
for c in s:
print(c)
关于python - “int”对象不可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11094664/