对于我的问题,我有一个非常简单的例子:
import re
my_string = re.sub(r"Hello", r"\Greetings", "Hello Folks!")
print(my_string)
在 Python 3.6 中,上面的代码会将 \Greetings Folks!
打印到标准输出。让我们在 Python 3.7.0 或 3.7.4(我能够测试的版本)中再试一次。会发生什么?我们收到一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.7/re.py", line 192, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/usr/lib/python3.7/re.py", line 309, in _subx
template = _compile_repl(template, pattern)
File "/usr/lib/python3.7/re.py", line 300, in _compile_repl
return sre_parse.parse_template(repl, pattern)
File "/usr/lib/python3.7/sre_parse.py", line 1024, in parse_template
raise s.error('bad escape %s' % this, len(this))
re.error: bad escape \G at position 0
这是为什么?我错过了 Python 3.7 中的更改吗?解决这个问题的正确方法是什么?
最佳答案
是的,有变化。来自关于 re.sub
的文档:
Changed in version 3.7: Unknown escapes in repl consisting of
'\'
and an ASCII letter now are errors.
所以只需加倍反斜杠:
my_string = re.sub(r"Hello", r"\\Greetings", "Hello Folks!")
关于带有正则表达式的 Python 3.7 : Why can I no longer substitute with a string containing a backslash (\)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58260348/