0
我想在Python中創建一個簡單的「猜字」遊戲。我的輸出是一樣的東西:Python:試圖循環查找匹配字符的字符串
String: _____ _____
Guess a word: 'e'
String:_e__o __e_e
Guess a word: 'h'
(and so on)
String: hello there
我有一個函數來做到這一點,這個函數中我有這樣的代碼:
def guessing(word):
count = 0
blanks = "_" * len(word)
letters_used = "" #empty string
while count<len(word):
guess = raw_input("Guess a letter:")
blanks = list(blanks)
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz "):
print "Please only guess letters!"
#Checks if guess is found in word
if guess in word and guess not in letters_used:
x = word.index(guess)
for x in blanks:
blanks[x] = guess
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-counter
print "There are", str(word.count(guess)) + str(guess)
guess
是原始輸入我從用戶那裏得到的一個猜測,並且letters_used
僅僅是用戶已經輸入的猜測集合。我想要做的是根據word.index(guess)
循環空白。不幸的是,這返回:
Guess a letter: e
e___
Yes, there are 1e
幫助將不勝感激!
什麼是'x'?請提供完整的可重複工作代碼。 –
@Anmol Singh Jaggi很抱歉。插入完整的代碼 – Nikitau