Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在每次查找下一个事件的while循环中使用索引_Python_String_Python 3.x_Indexing - Fatal编程技术网

Python 如何在每次查找下一个事件的while循环中使用索引

Python 如何在每次查找下一个事件的while循环中使用索引,python,string,python-3.x,indexing,Python,String,Python 3.x,Indexing,我想在一个字符串中找到一个字母的索引,然后替换同一索引中的字母,但在另一个字符串中,两个字符串都是字典的成员 但是,如果字符串中不止一次出现charStr(单个字符),它将只给出第一次出现的索引。如何使循环在每次运行时给出下一次出现的字符的索引,而不是第一次出现的字符的索引 抱歉,如果这没有意义,解释lol有点复杂,提前感谢您的帮助 index()方法采用第二个参数,指定开始搜索的位置 'abcbd'.index('b') # 1 'abcbd'.index('b', 1) # 1 'abcbd

我想在一个字符串中找到一个字母的索引,然后替换同一索引中的字母,但在另一个字符串中,两个字符串都是字典的成员

但是,如果字符串中不止一次出现charStr(单个字符),它将只给出第一次出现的索引。如何使循环在每次运行时给出下一次出现的字符的索引,而不是第一次出现的字符的索引

抱歉,如果这没有意义,解释lol有点复杂,提前感谢您的帮助

index()方法采用第二个参数,指定开始搜索的位置

'abcbd'.index('b') # 1
'abcbd'.index('b', 1) # 1
'abcbd'.index('b', 2) # 3
'abcbd'.index('b', 3) # 3
因此,在每次迭代中,可以使用
pos=x('secWord').index(charStr,pos+1)
。但是,如果子字符串不在字符串中,则会引发ValueError:

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

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
就你而言:

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

啊,我明白了,所以我可以做一个int变量,从0开始,然后在每个循环上加1?我如何避免值错误?我需要使用try-and-except块吗?@RJB查看最新编辑。。。如果您在之前检查计数,并且只进行
occ
迭代,则不会得到ValueError。抱歉,我刚刚抽出时间测试解决方案,但它实际上不起作用,您提供给我的信息是正确的,但我尝试使用您为我的案例提供的代码,当正确猜测字符时,它不会更新“curGuess”字符串