Bravi
Bravi

Reputation: 773

Convert string to unicode characters in python

Is it possible to convert a string to unicode characters in Python?

For example: Hello => \u0048\u0045\u004C\u004C\u004F

Upvotes: 0

Views: 586

Answers (1)

Jongware
Jongware

Reputation: 22447

You can't. A string already consists of 'Unicode characters'. What you want to change is not its representation but its actual contents.

That, fortunately, is as simple as

import re
text = 'Hello'
print (re.sub('.', lambda x: r'\u%04X' % ord(x.group()), text))

which outputs

\u0048\u0065\u006C\u006C\u006F

Upvotes: 1

Related Questions