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
Post a Comment