regex sub 在 python 中抛出一些错误

regex sub is throwing some error in python

我正在尝试使用 python 中的 re.sub 将字符替换为空行,但出现了一些错误

import re

string = "\asdfsdfsdf\dfd\f\df\df\d"
re.sub("\","",string)
print (string)

输出:

Traceback (most recent call last):
  File "variable_concat.py", line 4, in <module>
    re.sub("\","",string)
  File "/usr/lib/python2.7/re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/usr/lib/python2.7/re.py", line 244, in _compile
    raise error, v # invalid expression
sre_constants.error: bogus escape (end of line)

哪里出错了

您需要定义输入字符串以及原始字符串表示法形式的模式。

>>> string = r"\asdfsdfsdf\dfd\f\df\df\d"
>>> print(string)
\asdfsdfsdf\dfd\f\df\df\d
>>> re.sub(r"\","",string)
'asdfsdfsdfdfdfdfdfd'

如果输入的字符串没有被定义为raw string,字符串中的\a会变成unicode字符。