我有一个浏览器,它向我的Python服务器发送utf-8字符,但当我从查询字符串中检索它时,Python返回的编码是ASCII。如何将普通字符串转换为utf-8?

注意:从web传递的字符串已经被UTF-8编码,我只是想让Python将其视为UTF-8而不是ASCII。


当前回答

在Python 2中

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

^这是字节字符串(plain_string)和unicode字符串之间的区别。

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

^转换为unicode并指定编码。

Python 3

所有字符串都是unicode。unicode函数不再存在。参见@本体的回答

其他回答

如果上面的方法不起作用,你也可以告诉Python忽略字符串中不能转换为utf-8的部分:

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

在Python 3.6中,它们没有内置的unicode()方法。 字符串在默认情况下已经存储为unicode,不需要进行转换。例子:

my_str = "\u221a25"
print(my_str)
>>> √25

你可以使用python的标准库编解码器模块。

import codecs
codecs.decode(b'Decode me', 'utf-8')

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

将字节字符串转换为unicode字符串称为解码(unicode ->字节字符串是编码)。

可以通过使用unicode函数或decode方法来实现。:

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

Or:

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

你还可以这样做:

from unidecode import unidecode
unidecode(yourStringtoDecode)