如何在此代码中替换元音?

时间:2018-02-26 20:04:53

标签: python

我正在创造一个"猜单词"我的编程课程介绍游戏。它使用并行元组,其中一个列表是随机单词&第二个列表是这些单词的相应提示。该游戏应该打印一个带有下划线的随机单词代替元音(例如:J_p_n而不是日本),并且用户猜测该单词基于该&提示。使用我当前的代码,它不会在没有元音的情况下打印单词,而只是打印一个字母。我该如何解决这个问题?

import random

#Parallel tuples
guesswords = ("Japan","France","Mexico","Italy")
guesshints = ("Sushi comes from here","Croissants come from here","Tacos come from here","Pizza comes from here") 

#Variables
new_words = ""
vowels = "AaEeIiOoUu"

#Random
index = random.randrange(len(guesswords))
guesses = 5


#Replacing vowels
for letter in guesswords:
    if letter not in vowels:
        new_words += letter
    else:
        new_words += "_"

#Output        
print(new_words[index].center(80, " "))
print("Hint:",guesshints[index])
while guesses > 0:
    input_string = "\nGuess the word! You have " + str(guesses) + " guesses remaining: "
    user_guess = input(input_string)
    if user_guess.upper() == guesswords[index].upper():
        print("YOU WIN")
        break
    guesses -= 1

print("GAME OVER")

3 个答案:

答案 0 :(得分:1)

使用正则表达式可能是最简单的解决方案:

partitioner.class

结果:

import re
original_word = 'America'
vowels = re.compile(r'[aeiou]', re.IGNORECASE)
with_underscores = re.sub(vowels, '_', original_word)
print with_underscores

答案 1 :(得分:0)

而不是重建单词,你可以尝试这样的东西

for v in vowels:
    word = word.replace(v,'_')

答案 2 :(得分:0)

for letter in guesswords:更改为for letter in guesswords[index]:。并从此行[index]

中删除print(new_words[index].center(80, " "))