Search code examples
pythonasciiord

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


Solution

  • 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.