Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I have a string that will have digits in that, we need to remove all the characters which are not digits and replace the digits with #

I have written a regex, its able to replace the digits with #, but I could not find the regex to remove the characters which are not digits.

import re

def replace_digits(string):

    m=re.sub("\d","#",string)

Examples :

234 -> ###

a2b3c4 -> ###

abc -> <empty string>

#2a$#b%c%561# -> ####

1 Answer

0 votes
by (25.1k points)

You can just use the following code: 

for example in examples:

    new_s = '#' * len([x for x in example if x.isdigit()])

    print('Input = {} Output = {}'.format(example, new_s))

Related questions

+1 vote
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...