在Python3中,如何从UTF-16代码点获取字符?

在Python3中,如何从UTF-16代码点获取字符?,python,python-3.x,utf-16,Python,Python 3.x,Utf 16,我有一个UTF-16代码点列表,需要将这些代码点转换为它们以编程方式表示的实际字符。这在Python3中似乎难以做到 例如,我有一个字符的数字55357和56501,我知道这是钞票表情:下面的代码工作: cp1 = 55357 cp2 = 56501 (chr(cp1) + chr(cp2)).encode('utf-16', 'surrogatepass').decode('utf-16') #The trick is not to mess with chr but rather to co

我有一个UTF-16代码点列表,需要将这些代码点转换为它们以编程方式表示的实际字符。这在Python3中似乎难以做到


例如,我有一个字符的数字55357和56501,我知道这是钞票表情:下面的代码工作:

cp1 = 55357
cp2 = 56501
(chr(cp1) + chr(cp2)).encode('utf-16', 'surrogatepass').decode('utf-16')
#The trick is not to mess with 
chr
but rather to convert to a byte array, which you can then decode into a string:

a, b = 55357, 56501
x = a.to_bytes(2, 'little') + b.to_bytes(2, 'little')

print(x.decode('UTF-16'))
cp1=55357
cp2=56501
(chr(cp1)+chr(cp2))。编码('utf-16','subrogatepass')。解码('utf-16'))

# 诀窍不是乱处理
chr
,而是将其转换为字节数组,然后将其解码为字符串:

data = [55357, 56501]
b = bytes([x for c in data for x in c.to_bytes(2, 'little')])
result = b.decode('utf-16')
这可以推广到任意数量的整数:

chr(55357)+chr(56501)
这样的东西不起作用的原因是
chr
假定没有编码。它在原始Unicode代码点上工作,因此您要组合两个不同的字符。正如另一个答案所指出的,然后你必须对这两个字符串进行编码并重新解码,或者按照我的建议得到字节并解码一次