1

I have an unicode string κανω but due to some preprocessing from some other software that I can't change it becomes a literal string '\u03ba\u03b1\u03bd\u03c9' instead of u'\u03ba\u03b1\u03bd\u03c9'.

How could I change '\u03ba\u03b1\u03bd\u03c9' back to u'\u03ba\u03b1\u03bd\u03c9'?

I've tried:

>>> x = '\u03ba\u03b1\u03bd\u03c9'
>>> print x
\u03ba\u03b1\u03bd\u03c9
>>> print x.decode('utf8')
\u03ba\u03b1\u03bd\u03c9
>>> print x.encode('utf8')
\u03ba\u03b1\u03bd\u03c9
>>> print unicode(x)
\u03ba\u03b1\u03bd\u03c9

I cannot possibly go to each string output and add the u'...', i.e. I need to avoid doing this:

>>> x = u'\u03ba\u03b1\u03bd\u03c9'
>>> print x
κανω
alvas
  • 115,346
  • 109
  • 446
  • 738
  • 1
    There are many string formats that include `\u` escapes and if you use a decoder that doesn't match the encoder (eg if you decoded a JSON string with the Python-specific `unicode-escape`) then you are likely to end up with mangled results for some corner cases. Suggest you find out more specifics about the format... for example how does it output a backslash, or a newline, a zero byte, or a character in the range 0080–00FF? – bobince Jan 02 '15 at 17:23

1 Answers1

4

You need 'unicode_escape' (Produce a string that is suitable as Unicode literal in Python source code) as its encoding :

>>> s='\u03ba\u03b1\u03bd\u03c9'
>>> print unicode(s,'unicode_escape')
κανω
Mazdak
  • 105,000
  • 18
  • 159
  • 188