添加反斜杠而不转义

2024-10-05 14:24:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要对字符串中的&(与符)字符进行转义。问题是每当Istring = string.replace ('&', '\&')时,结果就是'\\&'。添加额外的反斜杠以转义原始反斜杠。如何删除这个额外的反斜杠


Tags: 字符串string字符replace斜杠istring
3条回答

Python以一种特殊的方式处理文字字符串中的\
这样您就可以键入'\n'表示换行'\t'表示选项卡
由于'\&'对Python没有任何特殊意义,Python词法分析器不会导致错误,而是隐式地为您添加额外的\

实际上,最好使用\\&r'\&'而不是'\&'

这里的r表示原始字符串,并且表示\不被特别处理,除非它正好位于字符串开头的引号字符之前

在交互控制台中,Python使用repr来显示结果,这就是为什么您会看到双'\'。如果您print您的字符串或使用len(string),您将看到它实际上只有2个字符

一些例子

>>> 'Here\'s a backslash: \\'
"Here's a backslash: \\"
>>> print 'Here\'s a backslash: \\'
Here's a backslash: \
>>> 'Here\'s a backslash: \\. Here\'s a double quote: ".'
'Here\'s a backslash: \\. Here\'s a double quote: ".'
>>> print 'Here\'s a backslash: \\. Here\'s a double quote: ".'
Here's a backslash: \. Here's a double quote ".

要澄清Peter在其评论中提出的观点,请参见this link

Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences marked as “(Unicode only)” in the table above fall into the category of unrecognized escapes for non-Unicode string literals.

结果'\\&'仅显示-实际上字符串是\&

>>> str = '&'
>>> new_str = str.replace('&', '\&')
>>> new_str
'\\&'
>>> print new_str
\&

把它放在贝壳里试试

实际上没有添加额外的反斜杠;它只是由repr()函数添加的,以指示它是一个文本反斜杠。当需要打印表达式的结果时,Python解释器使用repr()函数(调用对象上的__repr__()):

>>> '\\'
'\\'
>>> print '\\'
\
>>> print '\\'.__repr__()
'\\'

相关问题 更多 >