0

I have a list of strings, and I want to get the ascii codes of each character in each string. I'm looking to use list comprehension to do it all in one line. however, I can't get the syntax to work.

it works ok to get the codes for a singe word:

in:[ord(x) for x in 'hello']
out:[104, 101, 108, 108, 111]

obviously, the list comprehension can deal with returning a string from a list of strings:

in:[salutation for salutation in ['hello', 'goodbye']] 
out:['hello', 'goodbye']

but nesting these does not work:

in:[ord(x) for x in [salutation for salutation in ['hello', 'goodbye']]]
out:Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
TypeError: ord() expected a character, but string of length 5 found

How do I properly nest a list comprehension such that the inner portion will return a string which the outer portion can then interpret character by character?

Michael James
  • 492
  • 1
  • 6
  • 19

0 Answers0