replace all characters in a string with asterisks

后端 未结 4 635
旧巷少年郎
旧巷少年郎 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'.

    0 讨论(0)
  • 2020-12-20 19:30

    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'
    
    0 讨论(0)
  • 2020-12-20 19:32

    Probably you are looking for something like this?

    def blankout(instr, r='*', s=1, e=-1):
        if '@' in instr:
            # Handle E-Mail addresses
            a = instr.split('@')
            if e == 0:
                e = len(instr)
            return instr.replace(a[0][s:e], r * (len(a[0][s:e])))
        if e == 0:
            e = len(instr)
        return instr.replace(instr[s:e], r * len(instr[s:e]))
    
    0 讨论(0)
  • 2020-12-20 19:42

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

    I will answer this question quite literally. There may be times when you may have to perform it as a single step particularly when utilizing it inside an expression

    You can leverage the str.translate method and use a 256 size translation table to mask all characters to asterix

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

    Note because string is non-mutable, it will create a new string inside of mutating the original one.

    0 讨论(0)
提交回复
热议问题