etayluz
etayluz

Reputation: 16416

Python: convert unicode character to corresponding Unicode string

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

Answers (5)

etayluz
etayluz

Reputation: 16416

I prefer my own answer which is clean and simple:

json.dumps(unicode_character)

Upvotes: 0

JosefZ
JosefZ

Reputation: 30103

Python Specific Encodings:

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

Vikram Cothur
Vikram Cothur

Reputation: 11

Something like this works

>>> hex(ord('ב'))
'0x5d1'

Upvotes: 1

womyat
womyat

Reputation: 1

decoded_string = "ב"
encoded_string = decoded_string.encode("utf-8")

Upvotes: -1

han solo
han solo

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

Related Questions