python - 错误 : bad escape (end of pattern) at position 0 while trying to replace to backslah

标签 python backslash

<分区>

我需要替换字符串中的单个反斜杠。 我正在尝试执行 '\' 但它给我双反斜杠。 当我执行 '\' 时,它会在位置 0 抛出错误 bad escape (end of pattern)

string = 'abrakadabra'
string.replace('a','\\')
#or
re.sub('a','\\','abrakadabra')

In [47]: string.replace('a','\'')
Out[47]: "'br'k'd'br'"

In [48]: string.replace('a','\')
 File "<ipython-input-48-e884682860ae>", line 1
string.replace('a','\')
                       ^

SyntaxError: EOL while scanning string literal

In [49]: string.replace('a','\\')
Out[49]: '\\br\\k\\d\\br\\'

In [50]: 

期待结果: \br\k\d\br\

最佳答案

你应该使用'\\\\',然后你将传递'\\'给re,它只是一个转义的反斜杠。

print(re.sub('a','\\\\','abrakadabra'))
# \br\k\d\br\

关于python - 错误 : bad escape (end of pattern) at position 0 while trying to replace to backslah,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56206117/

相关文章:

Python:使用正则表达式捕获双反斜杠 C 字符

asp.net - 如何转义查询字符串中的反斜杠

python - 如何设置目标参数来使用 scipy.optimize 解决多目标问题?

python - 具有不同 X 轴顺序的 Pandas groupby 图

python - 在 Django 中解压缩 Zip 文件

windows - 带有 Windows 斜线的 Grails 2.3.0 升级问题

python 正则表达式 : match a string with only one instance of a character

python - 从层次结构中的顶级类调用方法而不是覆盖

python - 为什么 glob 会忽略某些目录?

c++ - C++ 中的正则表达式和双反斜杠