简体   繁体   English

如何在for循环中为字符串打印空格而不是下划线

[英]How to print space instead of underline in for loop for a string

I currently have this code:我目前有这个代码:

word_hidden = ""  
word = "Hello there"
hide_word = "_"
for i in range(len(word)):
word_hidden += hide_word
print(f"Word: {word_hidden}")

Output: Output:

Word: ___________

Is there a way for me to print the space as a space in the output instead of an underline, like this:有没有办法让我将空格打印为 output 中的空格而不是下划线,如下所示:

Output: Output:

Word: _____ _____
word = "Hello there"
hide_word = "_"

word_hidden = ''.join({' ':' '}.get(ch, hide_word) for ch in word)
print(word_hidden)

Prints:印刷:

_____ _____

Or:或者:

word_hidden = ''
for ch in word:
    if ch == ' ':
        word_hidden += ch
    else:
        word_hidden += hide_word

print(word_hidden)

Prints:印刷:

_____ _____

You can split your word and run the loop over the list created like this.您可以拆分您的单词并在这样创建的列表上运行循环。 This would print an extra space at the end of the word too.这也会在单词的末尾打印一个额外的空格。

word_hidden = ""
word = "Hello There"
ls = word.split(" ")
hide_word = "_"

for item in ls:
    word_hidden += len(item)*hide_word
    word_hidden += " "
    
print (f"Word: {word_hidden}")

Regular expression should work fine.正则表达式应该可以正常工作。

import re
regex = re.compile('[a-zA-Z]')
regex.sub('_', 'Hello there')

output is: output 是:

'_____ _____'

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

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