从十六进制字符串 representation/enter 单反斜杠创建原始 unicode 字符

Create raw unicode character from hex string representation/enter single backslash

我想从字符串十六进制表示形式创建原始 unicode 字符。也就是说,我有一个字符串 s = '\u0222' 它将成为 'ş' 字符。

现在,如果我这样做就可以了

>>> s = '\u0222'
>>> print(s)
'Ȣ'

但是,如果我尝试进行串联,结果会是

>>> h = '0222'
>>> s = r'\u' + '0222'
>>> print(s)
\u0222
>>> s
'\u0222'

因为可以看出,字符串中实际是'\\u'而不是'\u'。如何从十六进制字符串创建 unicode 字符,或者如何输入真正的单反斜杠?

这比我最初预期的要难得多:

code = '0222'
uni_code = r'\u' + code
s = uni_code.encode().decode('unicode_escape')
print(s)

或者

code = b'0222'
uni_code = b'\u' + code
s = uni_code.decode('unicode_escape')
print(s)

输入 \u0222 仅用于字符串常量,Python 解释器会为该语法生成​​单个 Unicode 代码点。它并不意味着要手动构建。 chr() 函数用于生成 Unicode 代码点。以下适用于字符串或整数:

>>> chr(int('0222',16)) # convert string to int base 16
'Ȣ'
>>> chr(0x222)          # or just pass an integer.
'Ȣ'

仅供参考 ord() 是互补函数:

>>> hex(ord('Ȣ'))
'0x222'