如何在 Python 中将字符串转换为 utf-8 [英] How to convert a string to utf-8 in Python
问题描述
我有一个浏览器将 utf-8 字符发送到我的 Python 服务器,但是当我从查询字符串中检索它时,Python 返回的编码是 ASCII.如何将纯字符串转换为 utf-8?
注意:从网络传递过来的字符串已经是 UTF-8 编码的,我只是想让 Python 把它当作 UTF-8 而不是 ASCII.
In Python 2
<预><代码>>>>plain_string = "嗨!";>>>unicode_string = u嗨!">>>类型(plain_string),类型(unicode_string)(<type 'str'>, <type 'unicode'>)^ 这是字节串(plain_string)和unicode串的区别.
<预><代码>>>>s =你好!">>>u = unicode(s, utf-8")^ 转换为 unicode 并指定编码.
在 Python 3 中
所有字符串都是Unicode.unicode
函数不再存在.请参阅@Noumenon 的回答
I have a browser which sends utf-8 characters to my Python server, but when I retrieve it from the query string, the encoding that Python returns is ASCII. How can I convert the plain string to utf-8?
NOTE: The string passed from the web is already UTF-8 encoded, I just want to make Python to treat it as UTF-8 not ASCII.
In Python 2
>>> plain_string = "Hi!"
>>> unicode_string = u"Hi!"
>>> type(plain_string), type(unicode_string)
(<type 'str'>, <type 'unicode'>)
^ This is the difference between a byte string (plain_string) and a unicode string.
>>> s = "Hello!"
>>> u = unicode(s, "utf-8")
^ Converting to unicode and specifying the encoding.
In Python 3
All strings are unicode. The unicode
function does not exist anymore. See answer from @Noumenon
这篇关于如何在 Python 中将字符串转换为 utf-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!