简体   繁体   中英

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:

Word: ___________

Is there a way for me to print the space as a space in the output instead of an underline, like this:

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:

'_____ _____'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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