Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replication of digits in a string using regex sub (Python)

Tags:

python

regex

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)
like image 674
Avo Asatryan Avatar asked Jan 29 '23 16:01

Avo Asatryan


1 Answers

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'
like image 110
Psidom Avatar answered Feb 02 '23 10:02

Psidom