python - how to replace regular expression based on the match results (e.g. a special function)? -


i have search expression 1-2 groups.

i need substitute each result depends on result value.

e.g. in following string, replace each matched digit it's value * 3.

s = 'a4cd5cd782cd' reg = '([1-9])cd' def f(x): return str(int(x)*3) 

expected result:

'a12cd15cd786cd' 

how can substitute function?

thanks

>>> import re >>> s = 'a4cd5cd782cd' >>> reg = r'([1-9])cd' >>> def f(x): return str(int(x.group(1))*3)+"cd" ... >>> re.sub(reg, f, s) 'a12cd15cd786cd' 

read the docs here.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -