Home > Back-end >  I want to convert multiple characters to Python regular expressions
I want to convert multiple characters to Python regular expressions

Time:12-03

I want to convert only numbers in this str

"ABC234TSY65234525erQ"

I tried to change only areas with numbers to the * sign

This is what I wanted

"ABC*TSY*erQ"

But when I actually did it, it came out like this

"ABC***TSY********erQ"

How do I change it?

Thanks you!

CodePudding user response:

use \d . in a regular expression means "match the preceding character one or more times"

import re
s = re.sub(r'\d ', '*', s)

output:

'ABC*TSY*erQ'

CodePudding user response:

The re.sub() solution given by @JayPeerachi is probably the best option, but we could also use re.findall() here:

inp = "ABC234TSY65234525erQ"
output = '*'.join(re.findall(r'\D ', inp))
print(output)  # ABC*TSY*erQ
  • Related