I want to convert multiple characters to Python regular expressions

Question:

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!

Asked By: ddjfjfj djfiejdn

||

Answers:

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'
Answered By: JayPeerachai

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
Answered By: Tim Biegeleisen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.