如何从代码点变量中获取 Unicode 字符?

How to get the Unicode character from a code point variable?

我有一个存储字符串 "u05e2" 的变量(该值不断变化,因为我将它设置在一个循环中)。我想打印具有该 Unicode 值的希伯来字母。我尝试了以下但没有用:

>>> a = 'u05e2'
>>> print(u'\{}'.format(a))

我得到的是 \u05e2 而不是 ע(在这种情况下)。

我也试过:

>>> a = 'u05e2'
>>> b = '\' + a
>>> print(u'{}'.format(b))

都没有成功。我该如何解决这个问题?

提前致谢!

发生这种情况是因为您必须在字符串外部添加后缀 u

a = u'\u05e2'
print(a)
ע

希望对您有所帮助。

您只需要 u05e2 之前的 \。要打印 Unicode 字符,您必须提供 Unicode 格式字符串。

a = '\u05e2'
print(u'{}'.format(a))

#Output
ע

当您通过在 print() 函数中打印 \ 来尝试其他方法时,Python 首先转义 \ 并且不会显示所需的结果。

a = 'u05e2'
print(u'\{}'.format(a))

#Output
\u05e2

验证 Unicode 格式字符串有效性的一种方法是使用 Python 标准库中的 ord() 内置函数。 returns 传递给它的字符的 Unicode 代码点(整数)。此函数只需要 Unicode 字符或表示 Unicode 字符的字符串。

a = '\u05e2'
print(ord(a)) #1506, the Unicode code point for the Unicode string stored in a

要打印上述 Unicode 代码值 (1506) 的 Unicode 字符,请使用带 c 的字符类型格式。 Python docs.

中对此进行了解释
print('{0:c}'.format(1506))

#Output
ע

如果我们将普通字符串文字传递给 ord(),我们会得到一个错误。这是因为此字符串不代表 Unicode 字符。

a = 'u05e2'
print(ord(a))

#Error
TypeError: ord() expected a character, but string of length 5 found

这看起来像 X-Y Problem。如果您想要代码点的 Unicode 字符,请使用整数变量和函数 chr(或 Python 2 上的 unichr),而不是尝试格式化转义码:

>>> for a in range(0x5e0,0x5eb):
...  print(hex(a),chr(a))
...
0x5e0 נ
0x5e1 ס
0x5e2 ע
0x5e3 ף
0x5e4 פ
0x5e5 ץ
0x5e6 צ
0x5e7 ק
0x5e8 ר
0x5e9 ש
0x5ea ת