I have a s="gh3wef2geh4ht"
. How can I receive s="gh333wef22geh4444ht"
by using sub. I have tried this regexp . what I am doing wrong?
s=re.sub(r"(\d)",r"\1{\1}",s)
You can use a lambda
function to capture the matched digits and repeat it:
s="gh3wef2geh4ht"
re.sub(r'(\d)', lambda m: m.group(1) * int(m.group(1)), s)
# 'gh333wef22geh4444ht'
You cannot use a regular expression pattern in the replacement pattern. The {...}
does not copy the text captured in Group 1 n times. You need to use a lambda expression or a callback method in the re.sub
to achieve what you want:
import re
s = 'gh3wef2geh4ht'
s=re.sub(r"\d", lambda m: m.group() * int(m.group()), s)
print(s)
See the Python demo
Note you do not need any capturing groups here, as the whole match is already available in Group 0.
Here, m
is assigned with the curren match object, m.group()
is the text value of the match and int(m.group())
is the digit cast to an int
. Thus, when 3
is matched, the lambda expression does just "3" * 3
and returns as the replacement.
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.