Replicating numbers in a string using regex sub (Python)

I have one s="gh3wef2geh4ht". How can I get s="gh333wef22geh4444ht"using sub. I tried this regex . what am I doing wrong?

s=re.sub(r"(\d)",r"\1{\1}",s)
+4
source share
2 answers

You cannot use a regular expression pattern in a replacement pattern. {...}Does not copy text shot in a group 1 n times. To achieve the desired result, you must use the lambda expression or the callback method in re.sub:

import re
s = 'gh3wef2geh4ht'
s=re.sub(r"\d", lambda m: m.group() * int(m.group()), s)
print(s)

See a Python demo

Note that you do not need capture groups here, since all matches are already available in group 0.

m curren, m.group() - , int(m.group()) - , int. , 3 , "3" * 3 .

+2

lambda :

s="gh3wef2geh4ht"
re.sub(r'(\d)', lambda m: m.group(1) * int(m.group(1)), s)
# 'gh333wef22geh4444ht'
+4

Source: https://habr.com/ru/post/1684979/


All Articles