[英]Replacing every instance of a character in Python string
我有一個用戶猜字母的游戲。 它們被顯示為神秘作品的空白版本(例如, _____
,_等於單詞中的字符數)。 該程序知道該單詞,並且如果他們猜測的字母存在於神秘單詞中,則需要替換該單詞的消隱版本中的每個索引。
例如,如果玩家猜到“p”並且單詞是“hippo”,則會顯示__pp_
。 但是,我的代碼只會替換第一個“p”實例,而是給出__p__
。
作為列表問題,這會更容易解決嗎?
mistakes = 0
complete = False
t = False
words = ['cow','horse','deer','elephant','lion','tiger','baboon','donkey','fox','giraffe']
print("\nWelcome to Hangman! Guess the mystery word with less than 6 mistakes!")
# Process to select word
word_num = valid_number()
word = words[word_num]
#print(word)
print("\nThe length of the word is: ", str(len(word)))
attempt = len(word)*"_"
# Guesses
while not (mistakes == 6):
guess = valid_guess()
for letter in word:
if guess == letter:
print("The letter is in the word.")
position = word.index(guess)
attempt = attempt [0:position] + guess + attempt [position + 1:]
print("Letters matched so far: ", attempt)
t = True
while (t == False):
print("The letter is not in the word.")
print("Letters matched so far: ", attempt)
mistakes = mistakes + 1
hangMan = ["------------", "| |", "| O", "| / |", "| |", "| / |\n|\n|"]
hang_man()
t = True
t = False
answer = 'hippo'
fake = '_'*len(answer) #This appears as _____, which is the place to guess
fake = list(fake) #This will convert fake to a list, so that we can access and change it.
guess = raw_input('What is your guess? ') #Takes input
for k in range(0, len(answer)): #For statement to loop over the answer (not really over the answer, but the numerical index of the answer)
if guess == answer[k] #If the guess is in the answer,
fake[k] = guess #change the fake to represent that, EACH TIME IT OCCURS
print ''.join(fake) #converts from list to string
這運行如下:
>>> What is your guess?
p
>>> __pp_
為了遍歷所有內容,我沒有使用index
,因為index
只返回第一個實例:
>>> var = 'puppy'
>>> var.index('p')
0
所以要做到這一點,我不是通過字母分析它,而是通過它的位置,使用for不會將k
作為每個字母,而是作為一個數字,以便我們可以有效地循環整個字符串而不返回只有一個變量。
也可以使用re
,但是對於初學程序員來說,最好理解某些東西是如何工作的,而不是從模塊中調用一堆函數(除了在隨機數的情況下, 沒有人想要制作他們自己的偽隨機方程: d)
import re
guess = valid_guess()
matches = [m.start() for m in re.finditer(guess, word)]
if matches:
for match in matches:
attempt = attempt[0:match] + guess + attempt[match+1:]
print("Letters matched so far: ", attempt)
else:
.
.
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.