3

I would like to ask how do the following conversion (source->target) by Python program.

>>> source = '\\x{4e8b}\\x{696d}'
>>> print source
\x{4e8b}\x{696d}
>>> print type(source)
<type 'str'>
>>> target = u'\u4e8b\u696d'
>>> print target.encode('utf-8')
事業

Thank you.

asked Mar 9, 2013 at 4:37
0

3 Answers 3

4

Taking advantage of Blender's idea, you could use re.sub with a callable replacement argument:

import re
def touni(match):
 return unichr(int(match.group(1), 16))
source = '\\x{4e8b}\\x{696d}'
print(re.sub(r'\\x\{([\da-f]+)\}', touni, source))

yields

事業
answered Mar 9, 2013 at 4:49
Sign up to request clarification or add additional context in comments.

2 Comments

I suppose you really wouldn't want restrict the matches only to codepoints that have lenght 4 if you are writing a conversion program. Otherwise +1.
@root: Yes, I suppose that was overly restrictive.
4

You can use int and unichr to convert them:

>>> int('4e8b', 16)
 20107
>>> unichr(int('4e8b', 16))
 u'\u4e8b'
>>> print unichr(int('4e8b', 16))
事
answered Mar 9, 2013 at 4:45

Comments

0
import re
p = re.compile(r'[\W\\x]+')
print ''.join([unichr(int(y, 16)) for y in p.split(source) if y != ''])
事業

also stole idea from @Blender...

answered Mar 9, 2013 at 4:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.