Comment convertir une liste de valeurs ascii en chaîne en python?
Question
J'ai une liste dans un programme Python qui contient une série de nombres, qui sont eux-mêmes des valeurs ASCII. Comment puis-je convertir cela en un "normal"? chaîne que je peux faire écho à l'écran?
La solution
Vous recherchez probablement 'chr ()':
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(chr(i) for i in L)
'hello, world'
Autres conseils
Même solution de base que les autres, mais je préfère personnellement utiliser map au lieu de la liste de compréhension:
>>> 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()
l = [83, 84, 65, 67, 75]
s = "".join([chr(c) for c in l])
print s
Peut-être pas comme une solution pyhtonique, mais plus facile à lire pour les noobs comme moi:
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 (): " " Salutations ! 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 ()
Vous pouvez utiliser octets (liste) .decode ()
pour ce faire - et liste (string.encode ())
pour obtenir les valeurs.
Question = [67, 121, 98, 101, 114, 71, 105, 114, 108, 122]
print(''.join(chr(number) for number in Question))