【问题标题】:Python converting latin1 to UTF8 [duplicate]Python将latin1转换为UTF8 [重复]
【发布时间】:2013-01-04 19:26:24
【问题描述】:

在 Python 2.7 中,如何将 latin1 字符串转换为 UTF-8。

例如,我正在尝试将 é 转换为 utf-8。

>>> "é"
'\xe9'
>>> u"é"
u'\xe9'
>>> u"é".encode('utf-8')
'\xc3\xa9'
>>> print u"é".encode('utf-8')
é

字母是é,它是拉丁小写字母E,带尖音(U+00E9) UTF-8 字节编码为:c3a9
拉丁字节编码为:e9

如何获得拉丁字符串的 UTF-8 编码版本?谁能举例说明如何转换é?

【问题讨论】:

  • 你读过Python Unicode HOWTO了吗?如果没有,你应该!
  • @MartijnPieters 我有,但编码总是有点混乱。

标签: python encoding utf-8 python-2.7 latin1


【解决方案1】:

要将字节序列从拉丁语 1 解码为 Unicode,请使用 .decode() method

>>> '\xe9'.decode('latin1')
u'\xe9'

Python 对\u00ff 以下的 unicode 代码点使用 \xab 转义。

>>> '\xe9'.decode('latin1') == u'\u00e9'
True

上面的 Latin-1 字符可以编码为 UTF-8 为:

>>> '\xe9'.decode('latin1').encode('utf8')
'\xc3\xa9'

【讨论】:

    【解决方案2】:
    >>> u"é".encode('utf-8')
    '\xc3\xa9'
    

    您有一个 UTF-8 编码的字节序列。不要尝试直接打印编码字节。要打印它们,您需要将编码字节解码回 Unicode 字符串。

    >>> u"é".encode('utf-8').decode('utf-8')
    u'\xe9'
    >>> print u"é".encode('utf-8').decode('utf-8')
    é
    

    请注意,编码和解码是相反的操作,可以有效地抵消。你最终得到了原始的u"é" 字符串,尽管Python 将它打印为等效的u'\xe9'

    >>> u"é" == u'\xe9'
    True
    

    【讨论】:

      【解决方案3】:

      concept = concept.encode('ascii', 'ignore') 概念 = MySQLdb.escape_string(concept.decode('latin1').encode('utf8').rstrip())

      我这样做,我不确定这是否是一个好方法,但它每次都有效!

      【讨论】:

        猜你喜欢
        • 2012-12-09
        • 1970-01-01
        • 2016-12-03
        • 2015-04-09
        • 2010-11-29
        • 2011-05-03
        • 2010-12-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多