RJB RJB - 1 year ago 62
Python Question

How to use index in a while loop which finds the next occurrence each time

I want to use '.index' as part of a while loop like the following:

def updateGame (x, charStr) :
occ = x('secWord').count(charStr)
charCount = 0
while occ > charCount :
pos = x('secWord').index(charStr)
x('curGuess')[pos] = charStr
charCount = charCount + 1

Argument x is a dictionary and argument charStr is a single character string.

I want to find the index of a letter in one string and then replace the letter in the same index but in another string, both strings are members of the dictionary.

however if there is more than one occurrence of the charStr (the single character) in the string it will only give the index of the first occurrence. How do I make it so that the loop would then give the index of the next occurrence of the character instead of just the first occurrence each time the loop runs?

Sorry if this doesnt make sense, Its a bit complicated to explain lol, thanks in advance for any help!

Answer Source

The index() method takes a second argument that specifies the position at which you start searching.

'abcbd'.index('b') # 1
'abcbd'.index('b', 1) # 1
'abcbd'.index('b', 2) # 3
'abcbd'.index('b', 3) # 3

So at each iteration, you can use pos = x('secWord').index(charStr, pos+1). However, if the substring is not in the string, it will raise a ValueError:

'abcbd'.index('b', 4) # ValueError: substring not found

For example:

astr = 'abcdbfrgbzb'
charStr = 'b'
occ = astr.count(charStr)
pos = -1
for _ in range(occ):
    pos = astr.index(charStr, pos+1)
    print pos
# 1, 4, 8, 10

In your case:

def updateGame (x, charStr) :
    occ = x('secWord').count(charStr)
    pos = -1
    for _ in range(occ):
        pos = x('secWord').index(charStr, pos+1)
        x('curGuess')[pos] = charStr
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download