如何在Python中将string转换为utf-8

我有一个浏览器发送UTF-8字符到我的Python服务器,但是当我从查询string中检索它时,Python返回的编码是ASCII。 我怎样才能将纯string转换为utf-8?

注:从networking传递的string已经是UTF-8编码,我只是想让Python把它作为UTF-8而不是ASCII。

>>> plain_string = "Hi!" >>> unicode_string = u"Hi!" >>> type(plain_string), type(unicode_string) (<type 'str'>, <type 'unicode'>) 

^这是字节string(plain_string)和unicodestring之间的区别。

 >>> s = "Hello!" >>> u = unicode(s, "utf-8") 

^转换为Unicode并指定编码。

如果上述方法不起作用,那么也可以让Python忽略不能转换为utf-8的string部分:

 stringnamehere.decode('utf-8', 'ignore') 

可能有点矫枉过正,但是当我在同一个文件中使用ascii和unicode时,重复解码可能是一个痛苦,这是我使用的:

 def make_unicode(input): if type(input) != unicode: input = input.decode('utf-8') return input else: return input 

如果我理解正确,你的代码中有一个utf-8编码的字节串。

将字节string转换为unicodestring称为解码(unicode – >string是编码)。

您可以使用unicode函数或解码方法来做到这一点。 或者:

 unicodestr = unicode(bytestr, encoding) unicodestr = unicode(bytestr, "utf-8") 

要么:

 unicodestr = bytestr.decode(encoding) unicodestr = bytestr.decode("utf-8") 

将以下行添加到.py文件的顶部:

 # -*- coding: utf-8 -*- 

允许您直接在脚本中编码string,如下所示:

 utfstr = "ボールト" 

在Python 3.6中,它们没有内置的unicode()函数。 要将string转换为unicode,只需获取该字符的Unicode值,然后执行以下操作:

 my_str = "\u221a25" my_str = u"{}".format(my_str) print(my_str) >>> √25 
 city = 'Ribeir\xc3\xa3o Preto' print city.decode('cp1252').encode('utf-8') 

使用ord()和unichar()进行转换。 每个Unicode字符都有一个数字,像索引。 所以Python有一些方法可以在字符和数字之间进行转换。 下行是一个例子。 希望它可以帮助。

 >>> C = 'ñ' >>> U = C.decode('utf8') >>> U u'\xf1' >>> ord(U) 241 >>> unichr(241) u'\xf1' >>> print unichr(241).encode('utf8') ñ