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!
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'
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
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!
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'
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