在Hangman-python3的列表中查找重复字符
对于我的hangman应用程序,代码如下:在Hangman-python3的列表中查找重复字符,python,list,Python,List,对于我的hangman应用程序,代码如下: text=list(input("Enter the word to be guessed:")) guess=[] tries=5 clue=input("Enter a clue: ") print('RULES:\n 1) type exit to exit applcation \n 2) type ? for the clue') for i in range(len(text)): t='_ ' guess.append(
text=list(input("Enter the word to be guessed:"))
guess=[]
tries=5
clue=input("Enter a clue: ")
print('RULES:\n 1) type exit to exit applcation \n 2) type ? for the clue')
for i in range(len(text)):
t='_ '
guess.append(t)
print(guess)
while True:
g=input("Guess a letter: ")
if g in text:
print("you guessed correct")
y=text.index(g)
guess[y]=g
print(guess)
continue
elif g=='exit':
exit()
elif g=='?':
print(clue)
elif tries==0:
print ("you have run out of tries, bye bye")
exit()
else:
print(g,' is not in the word')
tries -=1
print("you have",tries,'tries left')
continue
例如,对于代码,如果要猜测的文本是“阿凡达”,当猜测“a”时,它将只返回字母的第一个实例,而不返回位置;text[2][4]您可以使用正则表达式查找模式的索引
>>import re
>> [i.start() for i in re.finditer('a', 'avatar')]
[0, 2, 4]
您的问题来自于使用
y=text.index(g)
。这将只返回它找到的第一个匹配项的索引。您需要做一些类似于以下内容的事情:
if g in text:
print("you guessed correct")
for y in range(len(text)):
if text[y] == g:
guess[y] = g
print(guess)
出于某些对我不起作用的原因,Python3.x?y=[i.start()for i in re.finditer(g,text)]文件“/Users/-/anaconda/lib/Python3.5/re.py”,finditer中的第220行返回编译(模式,标志)。finditer(字符串)TypeError:预期的字符串或字节,如Objects当
文本
仍然是列表
时,此选项将不起作用。理想情况下,您需要更改为text=input(“输入要猜测的单词:”)
,然后应该能够使用[i.start()for i in re.finditer(g,text)]
,这是因为您将输入作为列表传递给re.finditer,而re.finditer需要一个字符串。您可以使用''将列表转换为字符串。连接(文本)
。