如何将一列ascii值转换为python中的string?
我在Python程序中有一个包含一系列数字的列表,这些数字本身就是ASCII值。 如何将其转换为可以回显到屏幕的“常规”string?
你可能正在寻找'chr()':
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100] >>> ''.join(chr(i) for i in L) 'hello, world'
与其他人相同的基本解决scheme,但我个人更喜欢使用地图,而不是列表理解:
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100] >>> ''.join(map(chr,L)) 'hello, world'
import array def f7(list): return array.array('B', list).tostring()
来自Python模式 – 一个优化的轶事
l = [83, 84, 65, 67, 75] s = "".join([chr(c) for c in l]) print s
也许不是Pyhtonic的解决scheme,但更容易阅读像我这样的noobs:
charlist = [34, 38, 49, 67, 89, 45, 103, 105, 119, 125] mystring = "" for char in charlist: mystring = mystring + chr(char) print mystring
def working_ascii():“”“G reetings!71,114,101,101,116,105,110,103,115,33”“”
hello = [71, 114, 101, 101, 116, 105, 110, 103, 115, 33] pmsg = ''.join(chr(i) for i in hello) print(pmsg) for i in range(33, 256): print(" ascii: {0} char: {1}".format(i, chr(i)))
working_ascii()