我有一个浏览器,它将utf-8字符发送到我的Python服务器,但是当我从查询字符串中检索它时,Python返回的编码是ASCII。如何将普通字符串转换为utf-8?
注意:从web传递的字符串已经是UTF-8编码的,我只想让Python将其视为UTF-8而不是ASCII。
发布于 2010-11-15 16:31:41
在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的答案
发布于 2013-10-08 01:00:57
如果上述方法不起作用,您还可以告诉Python忽略字符串中无法转换为utf-8的部分:
stringnamehere.decode('utf-8', 'ignore')
发布于 2014-11-30 03:13:33
可能有点夸张,但当我在同一文件中使用ascii和unicode时,重复解码可能是一种痛苦,以下是我使用的:
def make_unicode(inp):
if type(inp) != unicode:
inp = inp.decode('utf-8')
return inp
https://stackoverflow.com/questions/4182603
复制相似问题