简体   繁体   English

错误:尝试替换为backslah时,位置0处的错误转义(模式结束)

[英]error: bad escape (end of pattern) at position 0 while trying to replace to backslah

I need to replace single backslash in my string. 我需要在字符串中替换单个反斜杠。 I'm trying to perform '\\' but it gives with me double backslash. 我正在尝试执行“ \\”,但是它给了我两个反斜杠。 When i'm performing '\\' it throw error bad escape (end of pattern) at position 0 当我执行'\\'时,它会在位置0抛出错误的错误转义(模式结束)

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 SyntaxError:扫描字符串文字时停产

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

In [50]: 

expecting for result: \\br\\k\\d\\br\\ 预期结果:\\ br \\ k \\ d \\ br \\

You should use '\\\\\\\\' , then you will pass '\\\\' to re, which is just one escaped backsalsh. 您应该使用'\\\\\\\\' ,然后将传递'\\\\'重新输入,这只是一个转义的backsalsh。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python正则表达式错误与元组。 使用列表。 错误的转义(模式结束) - Python regex error with tuple. Works with list. Bad escape (end of pattern) 如何修复 - 错误:错误转义 \u 在位置 0 - how to fix - error: bad escape \u at position 0 Python 3.7.4: 're.error: position 0 处的错误转义\s' - Python 3.7.4: 're.error: bad escape \s at position 0' spacy 问题:错误:错误转义 \\p 在位置 257 - Problem with spacy: error: bad escape \p at position 257 在Python中使用Regex将一个字符串替换为另一个字符串:错误:re.error:位置0处的逃逸\\ w错误 - Replacing one string with another string using Regex in Python: Error: re.error: bad escape \w at position 0 从 3.5.4 传递到 3.6.8 时,如何解决 Python 正则表达式错误“error bad escape \m at position 37” - how to resolve Python regex error "error bad escape \m at position 37", when passing from 3.5.4 to 3.6.8 错误:使用正则表达式模式时在 position 多次重复 - error: multiple repeat at position while using a regex pattern 错误:使用正则表达式在 Python 脚本中错误转义 - Error: bad escape in Python script with regex 什么原因导致Python错误&#39;糟糕逃脱\\ C&#39;? - What causes Python error 'bad escape \C'? Python / Regex-仅在字符串末尾被模式替换 - Python/Regex - Replace by pattern only at the end of string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM