Ian
Ian

Reputation: 13

Python: changing string values in lists into ascii values using append

Im trying to figure out how to produce a list (for each string), a list of ASCII values representing the characters in each of those strings.

EG. changing "hello", "world" so that it looks like:

[[104, 101, 108, 108, 111], [119, 111, 114, 108, 100]]

Heres my code so far:

words = ["hello", "world"]
ascii = []
for word in words:
    ascii_word = []
    for char in word:
        ascii_word.append(ord(char))
    ascii.append(ord(char))

print ascii_word, ascii

I know it doesnt work but I am struggling to make it function properly. Any help would be much appreciated. Thankyou

Upvotes: 1

Views: 1620

Answers (2)

Shashank
Shashank

Reputation: 13869

One way is to use a nested list comprehension:

>>> [[ord(c) for c in w] for w in ['hello', 'world']]
[[104, 101, 108, 108, 111], [119, 111, 114, 108, 100]]

This is simply a concise way of writing the following code:

outerlist = []
for w in ['hello', 'world']:
    innerlist = []
    for c in w:
        innerlist.append(ord(c))
    outerlist.append(innerlist)

Upvotes: 1

Mark Tolonen
Mark Tolonen

Reputation: 177481

You were close:

words = ["hello", "world"]
ascii = []
for word in words:
    ascii_word = []
    for char in word:
        ascii_word.append(ord(char))
    ascii.append(ascii_word)  # Change this line

print ascii # and only print this.

But look into list comprehensions and @Shashank's code.

Upvotes: 1

Related Questions