我有一个浏览器,它向我的Python服务器发送utf-8字符,但当我从查询字符串中检索它时,Python返回的编码是ASCII。如何将普通字符串转换为utf-8?
注意:从web传递的字符串已经被UTF-8编码,我只是想让Python将其视为UTF-8而不是ASCII。
我有一个浏览器,它向我的Python服务器发送utf-8字符,但当我从查询字符串中检索它时,Python返回的编码是ASCII。如何将普通字符串转换为utf-8?
注意:从web传递的字符串已经被UTF-8编码,我只是想让Python将其视为UTF-8而不是ASCII。
当前回答
city = 'Ribeir\xc3\xa3o Preto'
print city.decode('cp1252').encode('utf-8')
其他回答
在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函数不再存在。参见@本体的回答
如果我理解正确的话,您的代码中有一个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")
如果上面的方法不起作用,你也可以告诉Python忽略字符串中不能转换为utf-8的部分:
stringnamehere.decode('utf-8', 'ignore')
你可以使用python的标准库编解码器模块。
import codecs
codecs.decode(b'Decode me', 'utf-8')
在.py文件的顶部添加以下一行:
# -*- coding: utf-8 -*-
允许你在脚本中直接编码字符串,就像这样:
utfstr = "ボールト"