我有一个浏览器,它向我的Python服务器发送utf-8字符,但是当我从查询字符串中检索它时,Python返回的编码是ASCII . 如何将纯字符串转换为utf-8?
注意:从Web传递的字符串已经是UTF-8编码的,我只想让Python将其视为UTF-8而不是ASCII .
>>> 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忽略它无法转换为utf-8的字符串部分:
stringnamehere.decode('utf-8', 'ignore')
可能有点矫枉过正,但是当我在同一个文件中使用ascii和unicode时,重复解码可能会很麻烦,这就是我使用的:
def make_unicode(input): if type(input) != unicode: input = input.decode('utf-8') return input else: return input
如果我理解正确,你的代码中有一个utf-8编码的字节串 .
将字节字符串转换为unicode字符串称为解码(unicode - > byte-string is encoding) .
您可以使用unicode函数或decode方法执行此操作 . 或者:
unicodestr = unicode(bytestr, encoding) unicodestr = unicode(bytestr, "utf-8")
要么:
unicodestr = bytestr.decode(encoding) unicodestr = bytestr.decode("utf-8")
将以下行添加到.py文件的顶部:
# -*- coding: utf-8 -*-
允许您直接在脚本中编码字符串,如下所示:
utfstr = "ボールト"
city = 'Ribeir\xc3\xa3o Preto' print city.decode('cp1252').encode('utf-8')
在Python 3.6中,它们没有内置的unicode()函数 . 要将字符串转换为unicode,只需获取字符的unicode值,然后执行以下操作:
my_str = "\u221a25" my_str = u"{}".format(my_str) print(my_str) >>> √25
用ord()和unichar()翻译 . 每个unicode char都有一个相关的数字,类似于索引 . 所以Python有一些方法可以在char和他的数字之间进行转换 . 下行是一个例子 . 希望它可以提供帮助 .
>>> C = 'ñ' >>> U = C.decode('utf8') >>> U u'\xf1' >>> ord(U) 241 >>> unichr(241) u'\xf1' >>> print unichr(241).encode('utf8') ñ
8 回答
^这是字节字符串(plain_string)和unicode字符串之间的区别 .
^转换为unicode并指定编码 .
如果上面的方法不起作用,你也可以告诉Python忽略它无法转换为utf-8的字符串部分:
可能有点矫枉过正,但是当我在同一个文件中使用ascii和unicode时,重复解码可能会很麻烦,这就是我使用的:
如果我理解正确,你的代码中有一个utf-8编码的字节串 .
将字节字符串转换为unicode字符串称为解码(unicode - > byte-string is encoding) .
您可以使用unicode函数或decode方法执行此操作 . 或者:
要么:
将以下行添加到.py文件的顶部:
允许您直接在脚本中编码字符串,如下所示:
在Python 3.6中,它们没有内置的unicode()函数 . 要将字符串转换为unicode,只需获取字符的unicode值,然后执行以下操作:
用ord()和unichar()翻译 . 每个unicode char都有一个相关的数字,类似于索引 . 所以Python有一些方法可以在char和他的数字之间进行转换 . 下行是一个例子 . 希望它可以提供帮助 .