-2

Is it possible to convert a string of ASCII characters from a list of strings:

[['You '], ['have '], ['made '], ['my '], ['day.']]

I understand that the conversion is done using ord(i) as explained here. I just can't seem to figure out how to retain the list of list structure after the conversion that reads something like this:

[[ 1, 2, 3 ], [ 1, 2, 3, 4 ], etc. ]

Thank you!

nagymusic
  • 71
  • 4

2 Answers2

3

use list comprehension or maps to traverse into the inner elements and apply the ord function:

example:

# python 3 (py2 syntax slightly different)
x = [['You '], ['have '], ['made '], ['my '], ['day.']]
[list(map(ord, i[0])) for i in x]
# outputs
Out[41]:
[[89, 111, 117, 32],
 [104, 97, 118, 101, 32],
 [109, 97, 100, 101, 32],
 [109, 121, 32],
 [100, 97, 121, 46]]
Haleemur Ali
  • 26,718
  • 5
  • 61
  • 85
  • Thanks a lot! This is very helpful. Could you suggest how to implement this into a statement that would enable one to replace all values less than a certain value by None (32 => None), and then subtract the rest of the lists by another value? Something like: if number < 65: q = None, else q = number - 12? – nagymusic Nov 19 '18 at 16:31
1

You have two options:

  • Nest your list comprehension:

    [[ord(c) for c in nested[0]] for nested in outerlist]
    
  • In Python 3, you can encode the string to a bytes object, and convert that to a list. bytes objects are just sequences of integers, after all:

    [list(nested[0].encode('ascii')) for nested in outerlist]
    

    The Python 2 equivalent is to use the bytearray() type; for str (byte strings):

    [list(bytearray(nested[0])) for nested in outerlist]
    

In both cases I assume that your nested list contain just a single element each, a string.

Demo on Python 3.7:

>>> l = [['You '], ['have '], ['made '], ['my '], ['day.']]
>>> [[ord(c) for c in nested[0]] for nested in l]
[[89, 111, 117, 32], [104, 97, 118, 101, 32], [109, 97, 100, 101, 32], [109, 121, 32], [100, 97, 121, 46]]
>>> [list(nested[0].encode('ascii')) for nested in l]
[[89, 111, 117, 32], [104, 97, 118, 101, 32], [109, 97, 100, 101, 32], [109, 121, 32], [100, 97, 121, 46]]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343