replace all characters in a string with asterisks

后端 未结 4 661
旧巷少年郎
旧巷少年郎 2020-12-20 19:17

I have a string

name = \"Ben\"

that I turn into a list

word = list(name)

I want to replace the characters

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-20 19:21

    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'.

提交回复
热议问题