Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace all characters in a string with asterisks

Tags:

python

string

I have a string

name = "Ben"

that I turn into a list

word = list(name)

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

I tried using the .replace function, but that was too specific and didn't change all the characters at once.

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

like image 820
ToshibaA Avatar asked Nov 12 '15 03:11

ToshibaA


2 Answers

I want to replace the characters of the list w/ asterisks

Instead, create a new string object with only asterisks, like this

word = '*' * len(name)

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

>>> '*' * 3
'***'
>>> 'abc' * 3
'abcabcabc'
like image 184
thefourtheye Avatar answered Nov 04 '22 06:11

thefourtheye


You may replace the characters of the list with asterisks in the following ways:

Method 1

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

This method is better IMO because no extra resources are used as the elements of the list are literally "replaced" by asterisks.

Method 2

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

OR

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

In this method, a new list of the same length (containing only asterisks) is created and is assigned to 'word'.

like image 40
Pratanu Mandal Avatar answered Nov 04 '22 06:11

Pratanu Mandal