繁体   English   中英

替换Python字符串中每个字符的实例

[英]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)

基于在Python中查找所有出现的子字符串

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM