Simple Python sub -
i have following code:
import re temp = "c4" num = 5 temp = re.sub(r'(\w)\d',r'\1%s'%num, temp) print temp
i following error:
ps c:\...> .\try.py traceback (most recent call last): file "c:\...\try.py", line 10, in <module> temp = re.sub(r'(\w)\d',r'\1%s'%num, temp) file "c:\python27\lib\re.py", line 151, in sub return _compile(pattern, flags).sub(repl, string, count) file "c:\python27\lib\re.py", line 275, in filter return sre_parse.expand_template(template, match) file "c:\python27\lib\sre_parse.py", line 802, in expand_template raise error, "invalid group reference" sre_constants.error: invalid group reference
what doing wrong here?
r'\1%s'%num
becomes equivalent of r'\15
, looking group #15 doesn't exist. fix this, replace \1
in replacement \g<1>
, way isn't affected digits follow:
temp = re.sub(r'(\w)\d',r'\g<1>%s'%num, temp)
or alternatively, add new digit after performing replacement remove original digit:
temp = '%s%s' % (re.sub(r'(\w)\d', r'\1', temp), num)
Comments
Post a Comment