如何在Python中将字符串转换为utf-8 [英] How to convert a string to utf-8 in Python
本文介绍了如何在Python中将字符串转换为utf-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个浏览器,该浏览器将utf-8字符发送到我的Python服务器,但是当我从查询字符串中检索到它时,Python返回的编码为ASCII.如何将纯字符串转换为utf-8?
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?
注意:从网络传递的字符串已经是UTF-8编码的,我只想让Python将其视为UTF-8而不是ASCII.
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.
推荐答案
>>> plain_string = "Hi!"
>>> unicode_string = u"Hi!"
>>> type(plain_string), type(unicode_string)
(<type 'str'>, <type 'unicode'>)
^这是字节字符串(plain_string)和unicode字符串之间的区别.
^ This is the difference between a byte string (plain_string) and a unicode string.
>>> s = "Hello!"
>>> u = unicode(s, "utf-8")
^转换为unicode并指定编码.
^ Converting to unicode and specifying the encoding.
这篇关于如何在Python中将字符串转换为utf-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文