繁体   English   中英

Python替换不包括空格的字符

[英]Python replace characters excluding whitespaces

我已将单词更改为仍然存在空格的框,但我不确定如何制作,以便当玩家猜出正确的字母时,框会变成字母。

继承人我如何把它改成盒子。

currentphrase = random.choice(WOFphrases)
hiddenphrase = re.sub('[A-Z]', u'\u2610',currentphrase)

我尝试这样做,但即使是空格也被框替换了。

for letter in currentphrase:
    if letter in completedletters:
        print(letter,end='')
    else:
        print(u'\u2610',end='')

不要为此使用正则表达式。 您的第二个解决方案应该有效,只需为空格添加条件

# Sample input
current_phrase = 'I am a phrase with letters and whitespaces'
completed_letters = ['a', 'e', 'w']  # make sure the letters here are already in lower case so it's easy to test later

# Solution
for letter in current_phrase:
    if letter.isspace() or letter.lower() in completed_letters:
        print(letter, end='')
    else:
        print(u'\u2610', end='')

输出:

☐ a☐ a ☐☐☐a☐e w☐☐☐ ☐e☐☐e☐☐ a☐☐ w☐☐☐e☐☐a☐e☐

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM