0

I'm trying to convert a str string '\u4e2d\u56fd' to unicode u'\u4e2d\u56fd'. It's the same thing in python3, but how to do it in python2.7?

I have tried decode, encode, str, bytes, unicode and others, but they all didn't work.

a = '\u4e2d\u56fd'
b = u'\u4e2d\u56fd'
print a
print b

And the result of the code above is

\u4e2d\u56fd
中国

All I want to do is to convert a to b.

Thanks for any tip!

yatu
  • 86,083
  • 12
  • 84
  • 139
Woko
  • 1,521
  • 12
  • 16

2 Answers2

1

You need to use raw_unicode_escape codec. For example:

a = '\u4e2d\u56fd'
a = a.decode('raw_unicode_escape')
print a
中国
0

you should write in the header of .py file # -*- coding: utf-8 -*-

# -*- coding: utf-8 -*-
a = '\u4e2d\u56fd'
print a

or try that

import sys
reload(sys)
sys.setdefaultencoding('utf8')
frankegoesdown
  • 1,898
  • 1
  • 20
  • 38