如何在Python中将字符串转换为utf-8
我有一个浏览器,它向我的Python服务器发送utf-8字符,但当我从查询字符串中获取这些字符时,Python返回的编码却是ASCII。我该如何把这个普通字符串转换成utf-8呢?
注意:从网页传来的字符串已经是UTF-8编码的,我只是想让Python把它当作UTF-8处理,而不是ASCII。
13 个回答
25
这可能有点过于复杂,但当我在同一个文件中同时处理ascii和unicode时,反复解码会很麻烦,所以我用的是这个方法:
def make_unicode(inp):
if type(inp) != unicode:
inp = inp.decode('utf-8')
return inp
84
如果上面的方法都不管用,你还可以告诉Python忽略那些它无法转换成utf-8的字符串部分:
stringnamehere.decode('utf-8', 'ignore')
316
在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的回答。