用反斜杠错误替换字符-Python [英] Replace a character with backslash bug - Python

查看:72
本文介绍了用反斜杠错误替换字符-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这对我来说就像个虫子。我无法用单个反斜杠替换字符串中的字符:

This feels like a bug to me. I am unable to replace a character in a string with a single backslash:

>>>st = "a&b"
>>>st.replace('&','\\')
'a\\b'

我知道'\'不是合法的字符串,因为 \ 转义最后一个'
但是,我不希望结果为‘a\\b’;我希望它是‘a\b’

I know that '\' isn't a legitimate string because the \ escapes the last '. However, I don't want the result to be 'a\\b'; I want it to be 'a\b'. How is this possible?

推荐答案

您正在查看的字符串 representation 本身就是有效的Python字符串文字。

You are looking at the string representation, which is itself a valid Python string literal.

\\ 本身只是一个斜线,但显示为转义字符以使值成为有效的Python文字字符串。您可以将该字符串复制并粘贴回Python,它将产生相同的值。

The \\ is itself just one slash, but displayed as an escaped character to make the value a valid Python literal string. You can copy and paste that string back into Python and it'll produce the same value.

使用 print st.replace('&' ,'\\')查看显示的实际值,或测试结果值的长度:

Use print st.replace('&','\\') to see the actual value being displayed, or test for the length of the resulting value:

>>> st = "a&b"
>>> print st.replace('&','\\')
a\b
>>> len(st.replace('&','\\'))
3

这篇关于用反斜杠错误替换字符-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆