python - 字符串变量的索引方法,在条件循环内,未返回所需的结果

标签 python python-2.7

text = "iiiiiiWiiiiiiWWiiiiW"
for char in text:
    if (char == "W"):
        z = text.index(char)
        print z

我在使用上面的代码时遇到了问题。我没有得到我想要的回应。 我收到:

>>>9
>>>9
>>>9
>>>9

...而不是得到类似...

>>>9
>>>16
>>>17
>>>22

这让我很困惑:(请帮助并谢谢:)

最佳答案

text.index('W') 将始终返回 'W'text 中第一次出现的位置。你可以这样做:

text = "iiiiiiWiiiiiiWWiiiiW"
for pos, char in enumerate(text):
    if char == "W":
        print pos

关于python - 字符串变量的索引方法,在条件循环内,未返回所需的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37312362/

相关文章:

python - python 终端中 Gnuplot 的 ImportError

python - 是否可以在 portmidi/pyportmidi 中找出 MIDI 设备连接到哪个 USB 端口

postgresql - psycopg2 查询远程数据库

Python 2 无法获取键和值(字典和元组)

python - 在 TensorFlow 中,如何将 2 个参数输入到 session.run() 中

python - AttributeError: 'Tensor' 对象没有属性 '_keras_history'

Python:检索使用@property 注释的类实例的所有属性

python - 为什么使用 lambda 函数将其设为属性?

python - Latex 的 build_pdf 模块中的运行时错误 - python

python - 全局变量的值在 python 中的函数调用之间丢失