Bin Chen Bin Chen - 3 years ago 212
Python Question

python: how to convert a string to 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 I think, 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(otherwise there are some errors pop up)

Answer Source
>>> 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download