2016-11-17 30 views
-1

對於我的hangman應用程序,代碼如下所示;在Hangman-python3列表中找到重複字符

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」是猜到了,它會返回只有字母而不是職位初審;文本[2] [4]

回答

0

您的問題來自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) 
0

您可以使用正則表達式來查找模式的索引。

>>import re 
>> [i.start() for i in re.finditer('a', 'avatar')] 
[0, 2, 4] 
+0

由於某種原因,對我來說不會工作,代碼是否會運行Python3.x? – reuben

+0

你有什麼錯誤? – Vince

+0

y = [i.start()for i in re.finditer(g,text)] 文件「/Users/----/anaconda/lib/python3.5/re.py」,第220行,在finditer中 return _compile(pattern,flags).finditer(string) TypeError:期望的字符串或類似字節的對象 – reuben

相關問題