是否可以 chr() 一个字符串?

Is it possible to chr() a string?

我确定这个问题已经被问过了,所以请原谅我重复。

Python 的 chr() 函数 returns 1 序数值的 unicode 字符串表示。我怎样才能 return 一串序数的unicode字符串?例如:
约翰:
j - 106
o-111
小时 - 104
n - 110

完整的 unicode 字符串是:106111104110

我目前的方法是:

from textwrap import wrap
ct = "106111104110" # unicode string
Split = wrap(ct,3) # split into threes list
inInt = list(map(int, Split)) # convert list of string into list of int
answer=''.join([chr(num) for num in inInt]) # return unicode string for each 3 character string
print(answer)

以上工作正常,打印“john”。

然而,当该值的 unicode 少于 3 个字符或少于 100 个字符时,这不起作用。例如:
苹果:
一 - 97
p - 112
p - 112
l - 108
电子 - 101

完整的 unicode 字符串是:97112112108101

但是在做:

ct="97112112108101"
Split = wrap(ct,3) 
inInt = list(map(int, Split)) 
answer=''.join([chr(num) for num in inInt]) 
print(answer)

会打印ϋyyQ,因为a的unicode是97,只有2个字符。我不想只使用超过 100 个字符。

是否有 python 库具有我正在寻找的功能?非常感谢。

Unicode 代码点最多可以是六位十六进制数字或七位十进制数字,因此您可以使用前导零来保持一致性:

>>> ''.join(format(ord(x),'06x') for x in 'john')
'00006a00006f00006800006e'
>>> ''.join(chr(int(_[i:i+6],16)) for i in range(0,len(_),6))  # _ gets previous result from REPL.
'john'
>>> ''.join(format(ord(x),'06x') for x in '你好吗')
'004f6000597d005417'
>>> ''.join(chr(int(_[i:i+6],16)) for i in range(0,len(_),6))
'你好吗'

然而,典型的编码是对字节串进行的,所以先编码为UTF-8,然后可以使用bytes方法得到两位数的十六进制字符串:

>>> 'apple'.encode('utf8').hex()
'6170706c65'
>>> bytes.fromhex(_).decode()
'apple'
>>> '你好吗'.encode('utf8').hex()
'e4bda0e5a5bde59097'
>>> bytes.fromhex(_).decode('utf8')
'你好吗'