Python 的“for c in string”习惯用法很好,但有时您可能会检查并发现需要将一段字符串 say 传递给函数。
比如
str = "I am a <token>"
for ch in str:
if ch == '<':
# I need to know where in string we are now
有办法吗?或者对于这种事情我应该以不同的方式来做吗?
请您参考如下方法:
>>> for i, ch in enumerate(str):
print i, ch
Would print
0 I
1
2 a
...
在使用 str 作为变量名时,您还应该小心,因为这是内置类型的名称。
