Question

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?

Was it helpful?

Solution

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'

OTHER TIPS

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'
import array
def f7(list):
    return array.array('B', list).tostring()

from Python Patterns - An Optimization Anecdote

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

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

print s

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

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()

You can use bytes(list).decode() to do this - and list(string.encode()) to get the values back.

Question = [67, 121, 98, 101, 114, 71, 105, 114, 108, 122]
print(''.join(chr(number) for number in Question))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top