python - “int”对象不可迭代

标签 python string int iterable

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/

相关文章:

python - 使用 Python PIL 和 Windows API : how to deal with rounded corners? 的事件窗口屏幕截图

Python Pandas - 在不读取/重写整个文件的情况下编写新的 CSV 标题行

string - Rust 字符串不是字符串

python - 将变量类型转换为 unicode 字符串

java - 如何在 java 中编写代码来查看 char 是否为 int?

ios - 使用 block ?

python - Pandas 在每第 n 行后插入一个新行

python - 什么是(属性错误 : 'NoneType' object has no attribute '__array_interface__' ) mean?

java - 我的字符串排列算法不起作用

c++ - 带有 vsprintf (C++) 的查询助手的 MySQL 动态字符串大小