如何替换python中的特定字符?

时间:2015-10-16 02:20:58

标签: python

所以我正在尝试制作一个刽子手游戏。我有一个功能可以将您想要猜到的单词转换成下划线。因此,如果你的话是你的话,你最终得到:_ _ _ _ _

然后我有另一个函数将单词中的每个字符添加到数组中。我有一个功能,让你猜测,如果猜测是不正确的,它会带走你的生命(我正在使用生命系统,而我想出如何实现刽子手的绘图),并添加错误的字母到一个空数组。我的程序还检查你没有输入任何不是字母或字母不重复的东西。

我唯一的问题是,我想不出一种告诉计算机的方法,如果字母在单词中,它应该切换字母与你猜测的空白区域。所以说如果你的话是房子,你猜它应该返回的字母:

h _ _ _ _ 

如果我使用替换功能,它会用正确的字母替换每个下划线。关于我能做什么的任何建议?

这是我的代码:

import random
category = [('sports', 1), ('video games', 2), ('movies', 3)]
sports = ('football', 'baseball', 'basketball')
video_games = ('counter strike', 'doom', 'wolfenstein')
movies = ('star wars', 'indiana jones', 'lord of the rings')


def pick_category():
    print("For sports type 1, for video games type 2, for movies type 3")
    choice = int(input("Choose a category: "))
    if choice == 1:
        word = random.choice(sports)
    elif choice == 2:
        word = random.choice(video_games)
    elif choice == 3:
        word = random.choice(movies)
    else:
        print("Invalid input")
    return word
word = pick_category()

def convert_spaces(): #Turns every letter in the word into an empty space
    spaces = word
    for i in range(0, len(word)):
        if ord(word[i]) != 32:
            spaces = spaces.replace(word[i], '_ ')
    print(spaces)
    return spaces
convert_spaces()

def word_list(): # Appends every letter of the word into an array
    array = []
    for i in range(0, len(word)):
        array.append(word[i])
    print(array)
    return array

def guess():
    array = []
    lives = 9
    while lives != 0:
        n = input("Guess a letter ").lower()
        if ord(n) in range(96, 123):
            if n in array:
                print("That letter is already in use.")
            elif n not in word and n not in array:
                array.append(n)
                lives = lives - 1
        else:
            print("Invalid input, try again")
        convert_spaces()
        print("Used letters: ", array)
        print("Life counter: ", lives)
    return array
guess()

1 个答案:

答案 0 :(得分:0)

继承代码。由于不必要的强制转换导致程序崩溃,我摆脱了int s。只是重新设计逻辑,让它看起来和工作得很好,你几乎就在那里。

diff:https://www.diffchecker.com/fsojakzh

import random
import string

sports = ('football', 'baseball', 'basketball',)
video_games = ('counter strike', 'doom', 'wolfenstein',)
movies = ('star wars', 'indiana jones', 'lord of the rings',)


def pick_category():
    print("For sports type 1, for video games type 2, for movies type 3")
    choice = input("Choose a category: ")
    if choice == '1':
        word = random.choice(sports)
    elif choice == '2':
        word = random.choice(video_games)
    elif choice == '3':
        word = random.choice(movies)
    else:
        print("Invalid input")
    return word


def draw(word, guesses):
    missing = set(string.ascii_lowercase) - set(guesses)
    masked = "".join([l if l not in missing else '_' for l in word])
    print(masked)
    return masked


def main():
    word = pick_category()
    guesses = []
    lives = 9

    while lives:
        masked = draw(word, guesses)

        if masked == word:
            print('You won!')
            return 0

        n = input("Guess a letter: ").lower()
        if n in string.ascii_lowercase:
            if n in guesses:
                print("That letter is already in use.")
            elif n not in word:
                guesses.append(n)
                lives = lives - 1
            else:
                guesses.append(n)
        else:
            print("Invalid input, try again")

        print("Used letters: ", ', '.join(guesses))
        print("Life counter: ", lives)

    print('You lost!')
    return 1

if __name__ == '__main__':
    main()

======================== old ====================== ==

我会做这样的事情:

>>> import string
>>> secret = "this is my hangman"
>>> guesses = ['a', 'c', 'g']
>>> "".join([l if l not in set(string.ascii_lowercase) - set(guesses) else '_' for l in secret])
'____ __ __ _a_g_a_'
>>> guesses.append('i')
>>> "".join([l if l not in set(string.ascii_lowercase) - set(guesses) else '_' for l in secret])
'__i_ i_ __ _a_g_a_'

请注意,因为我们正在执行not instring.ascii_lowercase没有''(空格)自动处理。不需要为它创建一个黑客。