我有以下代码:
import re
Temp = "C4"
Num = 5
Temp = re.sub(r'(\w)\d',r'\1%s'%Num, Temp)
print Temp
我收到以下错误:
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
我在这里做错了什么?
答案 0 :(得分:2)
r'\1%s'%Num
相当于r'\15
,所以这实际上是在寻找显然不存在的第15组。要解决此问题,请使用\1
替换替换中的\g<1>
,这样就不会受到以下任何数字的影响:
Temp = re.sub(r'(\w)\d',r'\g<1>%s'%Num, Temp)
或者,在执行替换后添加新数字以删除原始数字:
Temp = '%s%s' % (re.sub(r'(\w)\d', r'\1', Temp), Num)