如何在Python中将字符串转换为utf-8


问题内容

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

注意:从网络传递的字符串已经是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功能不再存在。查看@Noumenon的答案