【问题标题】:Python Convert Unicode-Hex utf-8 strings to Unicode stringsPython 将 Unicode-Hex utf-8 字符串转换为 Unicode 字符串
【发布时间】:2011-09-30 11:36:45
【问题描述】:

s = u'Gaga\xe2\x80\x99s'但需要转换成t = u'Gaga\u2019s'

如何才能最好地做到这一点?

【问题讨论】:

    标签: python unicode utf-8


    【解决方案1】:
    s = u'Gaga\xe2\x80\x99s'
    t = u'Gaga\u2019s'
    x = s.encode('raw-unicode-escape').decode('utf-8')
    assert x==t
    
    print(x)
    

    产量

    Gaga’s
    

    【讨论】:

    • 我在 Windows 终端中看到“GagaÔÇÖs”
    • print repr(t) 仍然产生'Gaga\xe2\x80\x99s'
    • @rocksportrocker, @Acorn looks like he fixed that.
    • 谢谢! @rocksportrocker,也可以,但只能接受一个答案。
    • @dbv:在研究了更多之后,我认为 Mark Tolonen 有更好的答案。为了让 SO 在顶部报告最佳答案,请考虑改为接受 his answer
    【解决方案2】:

    无论您在何处解码原始字符串,它都可能使用 latin-1 或近亲解码。由于 latin-1 是 Unicode 的前 256 个代码点,因此有效:

    >>> s = u'Gaga\xe2\x80\x99s'
    >>> s.encode('latin-1').decode('utf8')
    u'Gaga\u2019s'
    

    【讨论】:

    • 嗨,如果我想反之亦然,将它从 unicode 表示形式转换为十六进制表示形式,因为我正在将数据发送到一些需要 unicode 数据为十六进制格式的系统。
    • @securecurve,可能是某种形式的编码。就您的具体要求和示例输入和输出提出问题。
    【解决方案3】:
    import codecs
    
    s = u"Gaga\xe2\x80\x99s"
    s_as_str = codecs.charmap_encode(s)[0]
    t = unicode(s_as_str, "utf-8")
    print t
    

    打印

    u'Gaga\u2019s'
    

    【讨论】:

    • 对此感到好奇。我在 2.7 或 3.3 Python 文档中没有看到 codecs.charmap_encode,链接?
    猜你喜欢
    • 2010-09-21
    • 2012-07-02
    • 2021-07-06
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多