2013-01-21 374 views
7

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

例如,我试图将é转换为utf-8。

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

字母为E,其与急性(U + 00E9)拉丁小字母E 的UTF-8字节编码为的是:c3a9
拉丁字节编码为:E9

如何做我得到一个拉丁字符串的UTF-8编码版本?有人可以举例说明如何转换é?

+0

你读过[Python Unicode HOWTO](http://docs.python.org/2/howto/unicode.html)了吗?如果没有,你应该! –

+0

@MartijnPieters我有,但编码总是有点混乱。 – Eugene

回答

6

为了解码从拉丁1为Unicode的字节序列,使用.decode() method

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

Python使用\xab逃逸下面\u00ff Unicode代码点。

>>> '\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') 
é 

注意,编码和解码是其有效地抵消相反的操作。尽管Python将其打印为等效的u'\xe9',但最终会返回原始的u"é"字符串。

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

概念= concept.encode( 'ASCII', '忽略')的概念= MySQLdb.escape_string(concept.decode( 'latin1的')。编码( 'UTF8')。rstrip()可以)

我这样做,我不知道如果这是一个好方法,但它每次都有效!