Replace all characters in the string with asterisks

I have a line

name = "Ben"

that I go to the list

word = list(name)

I want to replace the list characters with asterisks. How can i do this?

I tried to use the function .replace, but it was too specific and did not change all the characters at once.

I need a generic solution that will work for any string.

+4
source share
3 answers

I want to replace w / asterisks list characters

Instead, create a new string object with asterisks, for example

word = '*' * len(name)

In Python, you can propagate a string with a number to get the same string concatenated. For example,

>>> '*' * 3
'***'
>>> 'abc' * 3
'abcabcabc'
+9
source

You can replace the list characters with asterisks in the following ways:

Method 1

for i in range(len(word)):
    word[i]='*'

, , "" .

2

word = ['*'] * len(word)

word = list('*' * len(word))

( ) "word".

+2

. ?

. , ,

str.translate 256

>>> name = "Ben"
>>> name.translate("*"*256)
'***'

, , .

+1

Source: https://habr.com/ru/post/1615521/


All Articles