简体   繁体   中英

To replace the digits in the string with # and remove all the characters which are not digits

Replacing of a particular character with '#' but replacing is not happening.What is wrong in the code?

Input:

A="234"

for i in range (len(A)):

  if (A[i].isdigit()):

    print(A[i])

    A.replace(A[i],"#");

print(A)

output:

2
3
4
234

A.replace(A[i],"#") will only return another string, it will not override the original. Do this to override it:

A="234"

for i in range (len(A)):

  if (A[i].isdigit()):

    print(A[i])

    A = A.replace(A[i],"#");

print(A)

It'd probably be easier to use a regex with python's builtin re module. Then you could do this in two regexes.

re.sub(r'[^\d]', '', A)
re.sub(r'\d', '#', A)

For the code you ask about, the suggestion provided by @AnnZen (+1) is sound, though I would toss the semicolon and the extra parentheses. I'd also loop over the characters in the string rather than their indexes:

for c in A:
    if c.isdigit():
        A = A.replace(c, "#")

As far as solving the complete problem (ie adding elimination of non-digits), we don't actually need replace() :

def convert(string):
    result = ''

    for character in string:
        if character.isdigit():
            result += "#"

    return result

However, if we want to use replace() , this seems like an opportunity to also use a defaultdict :

from collections import defaultdict

dictionary = defaultdict(str, {digit: '#' for digit in "0123456789"})

def convert(string):
    for character in string:
        string = string.replace(character, dictionary[character])

    return string

We can tack on some test code to check it out:

if __name__ == "__main__":  # test code
    from random import choice, randint
    from string import ascii_letters, digits

    for tests in range(10):
        test_string = ''.join(choice(ascii_letters + digits) for _ in range(randint(10, 20)))

        print(repr(test_string), end=' -> ')

        test_string = convert(test_string)

        print(repr(test_string))

OUTPUT

> python3 test.py
'RzfMD5w3LQO' -> '##'
'NrFsFDDyOit593' -> '###'
'TpURdM0PqTQtaPe3IeP' -> '##'
'TN10mz39BukFNsgf' -> '###'
'ghYfxDLrPSEG5GCO' -> '#'
'9QAJ1PVyegMD' -> '#'
'GOIgOmzpC1ysn4' -> '#'
'LEdR2BafYi9paALgrN' -> '##'
'L2hzkSQNkH2Gb' -> '##'
'E6rnoGi2AamWW01R19' -> '####'
>

The regex idea of @duckboycool has merit, even if the currently suggested implementation doesn't. We don't need two pattern matches, just one to eliminate non-digits:

import re

def convert(string):
    return '#' * len(re.sub(r'\D', '', string))

Any of my various convert() funtions should work with my test code above.

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