0
st = "abXabXAbX"
ch = "A"
st = st.lower()
ch = ch.lower()


for i in st:
    if (i==ch):
       print st.find(i)

I am trying to position of the character "ch" in uppercase and lower case in the string "st". The for loop gets stuck at detecting the first "a", how do I get the loop to move on check the rest of the string?

3 Answers3

1

The for loop isn't stuck, but advancing as it should. You think it's stuck because find returns the first occurence of the item it looks for. It always encounters it at index 0, so your code prints 0, 0, 0.

For this to run, you can use enumerate to keep track of the index of the letter:

for i, ltr in enumerate(st):
    if (ltr==ch):
       print i
Korem
  • 11,383
  • 7
  • 55
  • 72
1
>>> st = "abXabXAbX".lower()
>>> ch = "A".lower()
>>> [ ix for ix,item in enumerate(st) if item == ch]
[0, 3, 6]
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
1
st = "abXabXAbX"
ch = "A"
st = st.lower()
ch = ch.lower()
pos = st.find(ch)
print(pos)

while pos >= 0:
    pos=st.find(ch,pos+1)
    if pos>-1:
        print(pos)

this will give you all positions

  • more elegant w/o the first print, and then `while pos>=0: print(pos); pos = st.find(ch, pos+1` – Korem Oct 28 '14 at 16:51