Python2.7将%(百分比)替换为\(斜杠),但得到\(双斜杠)

2024-10-03 17:27:35 发布

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

我想要这个结果:

u'\ue8fc\x82'

但它总是给我:

u'\\ue8fc\\u0082'

示例1:

>>> a='\ue8fc\u0082'

>>> a
'\\ue8fc\\u0082'

>>> print a
\ue8fc\u0082

>>> unicode(a)
u'\\ue8fc\\u0082'

>>> unicode(a).replace('\\\\','\\')
u'\\ue8fc\\u0082'

>>> repr(unicode(a).replace('\\\\','\\'))
"u'\\\\ue8fc\\\\u0082'"

>>> repr(unicode(b).replace('\\','?'))
"u'?ue8fc?u0082'"

>>> repr(unicode(b).replace('\\','?').replace('?','\\'))
"u'\\\\ue8fc\\\\u0082'"

样本2:

>>> u'\ue8fc\u0082'
u'\ue8fc\x82'

>>> repr(u'\ue8fc\u0082')
"u'\\ue8fc\\x82'"

我为什么需要这个:

我想转身

'%ue8fc%u0082'

进入

'\ue8fc\u0082'


Tags: 示例unicodereplace样本printx82repru0082
2条回答

这是正确的。\\代表一个反斜杠。这是字符串的unicode-escaped版本。你知道吗

使用以下代码转换为标准字符串:

>>> import codecs
>>> codec.decode("\\ue8fc\\u0082", "unicode-escape")
'\ue8fc\x82'

用于表示Unicode字符的反斜杠不是字符串的一部分,不能使用str.replace进行操作。但是,可以使用“unicode\u escape”编码将带有“real”反斜杠的字符串转换为转义字符串:

>>> s = "%ue8fc%u0082"
>>> s.replace("%", "\\").decode("unicode_escape")
u'\ue8fc\x82'

相关问题 更多 >