【问题标题】:Python 2.7 Replace % (Percentage) to \ (Slash) but got \\ (Double Slash)Python 2.7 将 %(百分比)替换为 \(斜杠)但得到了 \\(双斜杠)
【发布时间】:2019-03-18 15:59:23
【问题描述】:

我想要这个结果:

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'

【问题讨论】:

    标签: python python-2.7 replace slash


    【解决方案1】:

    用于表示 Unicode 字符的反斜杠实际上并不是字符串的一部分,并且不能使用 str.replace 进行操作。但是,可以使用“unicode_escape”编码将带有“真实”反斜杠的字符串转换为转义字符串:

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

    【讨论】:

    • 完整且很好的解释~谢谢。
    【解决方案2】:

    这是正确的。 \\ 代表单个反斜杠。这是字符串的unicode-escaped 版本。

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

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

    【讨论】:

    • 通俗易懂。非常感谢~
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2017-07-25
    • 2013-06-24
    • 1970-01-01
    相关资源
    最近更新 更多