如何在Python中将ascii值列表转换为字符串?

Ele*_*hoy 62 python string ascii

我在Python程序中有一个列表,其中包含一系列数字,这些数字本身就是ASCII值.如何将其转换为"常规"字符串,我可以回显到屏幕?

Tho*_*ers 116

你可能正在寻找'chr()':

>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(chr(i) for i in L)
'hello, world'
Run Code Online (Sandbox Code Playgroud)

  • 我敢打赌你用'[ord(x)代表'hello,world'中的x创建了那个列表L. (7认同)

小智 20

与其他人一样的基本解决方案,但我个人更喜欢使用map而不是list comprehension:


>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(map(chr,L))
'hello, world'
Run Code Online (Sandbox Code Playgroud)


Ton*_*uža 12

import array
def f7(list):
    return array.array('B', list).tostring()
Run Code Online (Sandbox Code Playgroud)

来自Python Patterns - 一个优化轶事


Tho*_*ele 6

l = [83, 84, 65, 67, 75]

s = "".join([chr(c) for c in l])

print s
Run Code Online (Sandbox Code Playgroud)


小智 5

也许不像 Pyhtonic 那样是一个解决方案,但对于像我这样的菜鸟来说更容易阅读:

charlist = [34, 38, 49, 67, 89, 45, 103, 105, 119, 125]
mystring = ""
for char in charlist:
    mystring = mystring + chr(char)
print mystring
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用它bytes(list).decode()来执行此操作并list(string.encode())取回值。