gpt4 book ai didi

python - 如何替换这段代码中的元音?

转载 作者:太空宇宙 更新时间:2023-11-03 14:04:34 25 4
gpt4 key购买 nike

我正在为我的编程入门类(class)创建一个“猜单词”游戏。它使用并行元组,其中一个列表是随机单词,第二个列表是这些单词的相应提示。游戏应该打印一个随机单词,用下划线代替元音(例如:J_p_n 而不是 Japan),用户根据该单词和提示猜测该单词。使用我当前的代码,它不会打印没有元音的单词,而是只打印一个字母。我该如何解决这个问题?

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")

最佳答案

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

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

结果:

_m_r_c_

关于python - 如何替换这段代码中的元音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48996240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com