NightFury13 NightFury13 - 20 days ago 7
Python Question

How to convert unicode representation of non-ascii string to a python string as is?

How can I convert the unicode-representation of a non-ascii range string to a python string?

> str = '<some-arabic-content>'
> decoded_str = str.decode('utf-8')
> decoded_str
u'\u0623\u0646\u0633\u0646\u0629'
> str(decoded_str)
<WILL-THROW-AN-ERROR-OFC> since ascii cannot encode the unicode string


How do I get the this representation ('\u0623\u0646\u0633\u0646\u0629') as a python string? Like the one below.

> str_rep = '\u0623\u0646\u0633\u0646\u0629'


I want to land on
str_rep
from
decoded_str
. How can I go about doing this?

Answer

decoded_str.encode("unicode-escape") produces the desired output.