简体   繁体   English

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

[英]Replacing every instance of a character in Python string

I have a game where the user guesses letters. 我有一个用户猜字母的游戏。 They are shown a blank version of the mystery work ( _____ for example, the _'s are equal to number of characters in the word). 它们被显示为神秘作品的空白版本(例如, _____ ,_等于单词中的字符数)。 The program knows the word, and needs to replace every index in the blanked out version of the word if the letter they guess is present in the mystery word. 该程序知道该单词,并且如果他们猜测的字母存在于神秘单词中,则需要替换该单词的消隐版本中的每个索引。

For example, if the player guesses "p" and the word is "hippo" they will be shown __pp_ . 例如,如果玩家猜到“p”并且单词是“hippo”,则会显示__pp_ But, my code will only replace the first instance of "p", giving __p__ instead. 但是,我的代码只会替换第一个“p”实例,而是给出__p__

Would this be easier to tackle as a list problem? 作为列表问题,这会更容易解决吗?

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

This runs as: 这运行如下:

>>> What is your guess?
p
>>> __pp_

To loop over everything, I did not use index , because index only returns the first instance: 为了遍历所有内容,我没有使用index ,因为index只返回第一个实例:

>>> var = 'puppy'
>>> var.index('p')
0

So to do that, I analyzed it not by the letter, but by its placement, using a for that does not put k as each letter, but rather as a number so that we can effectively loop over the entire string without it returning only one variable. 所以要做到这一点,我不是通过字母分析它,而是通过它的位置,使用for不会将k作为每个字母,而是作为一个数字,以便我们可以有效地循环整个字符串而不返回只有一个变量。

One could also use re , but for a beginning programmer, it is better to understand how something works rather than calling a bunch of functions from a module (except in the case of random numbers, nobody wants to make their own pseudo-random equation :D) 也可以使用re ,但是对于初学程序员来说,最好理解某些东西是如何工作的,而不是从模块中调用一堆函数(除了在随机数的情况下, 没有人想要制作他们自己的伪随机方程: d)

Based on Find all occurrences of a substring in Python : 基于在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