JoeS
JoeS

Reputation: 25

Index method for string variable, inside conditional loop, not returning desired results

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

I'm having a problem with the above code. I'm not getting my desired response. I am receiving:

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

...instead of getting something like...

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

This is confusing me :( please help and thanks :)

Upvotes: 1

Views: 22

Answers (1)

Simon Fromme
Simon Fromme

Reputation: 3174

text.index('W') will always return the position of the first occurence of 'W' in text. You could do it like that:

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

Upvotes: 1

Related Questions