I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You are probably looking for 'chr()':
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(chr(i) for i in L)
'hello, world'
回答2:
Same basic solution as others, but I personally prefer to use map instead of the list comprehension:
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(map(chr,L))
'hello, world'
回答3:
import array
def f7(list):
return array.array('B', list).tostring()
from Python Patterns - An Optimization Anecdote
回答4:
l = [83, 84, 65, 67, 75]
s = "".join([chr(c) for c in l])
print s
回答5:
Perhaps not as Pyhtonic a solution, but easier to read for noobs like me:
charlist = [34, 38, 49, 67, 89, 45, 103, 105, 119, 125]
mystring = ""
for char in charlist:
mystring = mystring + chr(char)
print mystring
回答6:
def working_ascii(): """ G r e e t i n g s ! 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()
回答7:
Question = [67, 121, 98, 101, 114, 71, 105, 114, 108, 122]
print(''.join(chr(number) for number in Question))