Reputation: 16416
How do I convert a unicode character 'ב' to its corresponding Unicode character string '\u05d1' in Python?
I asked the opposite question a few days ago: Python: convert unicode string to corresponding Unicode character
Upvotes: 3
Views: 848
Reputation: 16416
I prefer my own answer which is clean and simple:
json.dumps(unicode_character)
Upvotes: 0
Reputation: 30103
unicode_escape
- Encoding suitable as the contents of a Unicode literal in ASCII-encoded Python source code, except that quotes are not escaped.
'ב'.encode('unicode-escape').decode() ### '\\u05d1'
print('ב'.encode('unicode-escape').decode()) ### \u05d1
Upvotes: 1
Reputation: 6590
You can do something like,
>>> x
'ב'
>>> x.encode('ascii', 'backslashreplace').decode('utf-8')
'\\u05d1'
From the docs:
The errors parameter is the same as the parameter of the decode() method but supports a few more possible handlers. As well as 'strict', 'ignore', and 'replace' (which in this case inserts a question mark instead of the unencodable character), there is also 'xmlcharrefreplace' (inserts an XML character reference),
backslashreplace
(inserts a \uNNNN escape sequence) and namereplace (inserts a \N{...} escape sequence).
Upvotes: 1