Python:将unicode字符转换为相应的unicode字符串

2024-05-19 15:05:38 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Python中将unicode字符“ב”转换为其对应的unicode字符串“\u05d1”

几天前我问了一个相反的问题: Python: convert unicode string to corresponding Unicode character


Tags: to字符串convertstringunicode字符中将character
3条回答

你可以这样做

>>> x
'ב'
>>> x.encode('ascii', 'backslashreplace').decode('utf-8')
'\\u05d1'

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).

像这样的工作

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

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

相关问题 更多 >