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

时间:2014-02-27 05:23:22

标签: python

我有一个用户猜字母的游戏。它们显示为神秘作品的空白版本(例如_____,_'s等于单词中的字符数)。程序知道这个单词,并且如果他们猜到的字母出现在神秘词中,则需要替换该单词的空白版本中的每个索引。

例如,如果玩家猜到“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

2 个答案:

答案 0 :(得分:2)

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,但对于初级程序员来说,最好先理解一些东西是如何工作的,而不是从模块中调用一堆函数(除了随机数, nobody) 想要制作自己的伪随机方程式:D)

答案 1 :(得分:0)

基于Find all occurrences of a substring in 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:
    .
    .
    .