Monday, 2 May 2016

How to convert Unicode to Str in Python

Python
TypeError: expected unicode, got str

Strings are not the same as unicode in Python 2.
type("text")
>> <type 'str'>
type(u"text")
>> <type 'unicode'>
So, the conversions:
  • From unicode to str, use encode:
    u"text".encode('utf-8') == "text"
  • From str to unicode, use decode:
    "text".decode("utf-8") == u"text"

No comments:

Post a Comment