3

How can I convert a list into ASCII, but I want to have a list again after I converted it.

I found this for converting from ASCII to a list:

L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
print(''.join(map(chr,L)))

But it doesn't work reversed.

This is my input:

L = ['h','e','l','l','o']

And I want this as output:

L = ['104','101','108','108','111']
BOB
  • 59
  • 2
  • 8
  • `print(list(map(chr,L)))` ? So you'll have a list of each char converted to ascii (returns `['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']`). In fact, your `join` is joining each element of your map using `''` as separator. You don't want to join them if you want `a list again` as you said – Hearner Jul 25 '18 at 07:51
  • Yes that's my output, but I want to use ord(). Do you know how I do need to do it then? – BOB Jul 25 '18 at 07:54
  • You want to use `ord()` to transform your list of integers into list of ascii representation of these integers ? That's not what `ord()` do. Be more specific. Edit your question and say what you want to get as a result. What do you want to use `ord()` for ? – Hearner Jul 25 '18 at 07:55

7 Answers7

4

This is a much simpler solution:

L = ['h','e','l','l','o']
changer = [ord(x) for x in L]
print(changer)

Using the function ord()

Mahir Islam
  • 1,941
  • 2
  • 12
  • 33
2

This worked well for me.

>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> print [ chr(x) for x in L]
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
ItayBenHaim
  • 163
  • 7
2
L = ['h','e','l','l','o']

print(list(map(ord,L)))
#output : [104, 101, 108, 108, 111]

print(list(map(str,map(ord,L))))
#output : ['104', '101', '108', '108', '111']
Hearner
  • 2,711
  • 3
  • 17
  • 34
1
L = ['h','e','l','l','o']
print(list(map(str, map(ord, L))))

This outputs:

['104', '101', '108', '108', '111']
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

This works the other way round:

L = ['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
L = [ord(x) for x in L]
print(L)

output:

[104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
Jones1220
  • 786
  • 2
  • 11
  • 22
1

From here

You can try:

L = ['h','e','l','l','o']
for x in range(len(L)):
     L[x] = ord(L[x])
print(L)

Ouput:

[104,101,108,108,111]

EDIT:

ord() allows you to convert from char to ASCII whereas chr() allows you to do the opposite

Vex -
  • 19
  • 5
0
message = list(input("Message: "))
message = [ord(x) for x in message]
print(message)

Here is my solution for this. Hope this helps! Output depends on your input, but in general it will follow the form

[x, y, z]