如何用破折号(空格python)用破折号替换字符串中的字符

时间:2018-11-30 01:30:14

标签: python

因此,我目前正在制作(远未完成的)子手游戏。一切正常,除了我尝试用下划线替换随机选择的单词时。代码确实按我的要求用下划线替换了每个字符,但我希望它不要用破折号替换字符串中的空格。例如,如果随机选择的团队是“ New York Jets”,则python将其替换为“ _ _ _ _ _ _ _ _”  _ _ _ _“”而不是“ _ _ _(空格)_ _ _ _ _(空格)_ _ _ _”

我不明白自己做错了什么,我认为if语句可以解决问题,但不能解决问题。

        function Confirmation() {


        var txt;
        if (confirm("Are you sure you want an answer?){
            txt = "";
        } else {
            return false;
        }

到目前为止的所有代码

# doesn't replaces spaces with dash
if letter != " ":
  hide = "_ " * len(secret_word)

3 个答案:

答案 0 :(得分:1)

if letter != " ":
    hide = "_ " * len(secret_word)

基本上每个字母都进行相同的计算。 (因为len(secret_word)与当前正在处理的字符无关)

您想要做的是:

#hides the word with underscore
hide = ""
for letter in secret_word:
    # doesnt replaces spaces with dash
    if letter != " ":
            hide = hide + "_"
    else:
            hide = hide + " "
print(hide)

或者,阅读python中的正则表达式和string.replace()函数。

答案 1 :(得分:1)

正则表达式?

import re
hide = re.sub(r'\S', '_', secret_word)

答案 2 :(得分:0)

可以为自己编写一些辅助功能,例如:

def dashify(str):
    return "".join("-" if char is not " " else " " for char in str)