Python: changing string values ​​in lists to ascii values

I am trying to convert characters in a string to individual ascii values. I can't seem to get every single character to change its relative ascii value.

For example, if the word variables have the value ["hello", "world"], after running the completed code, the ascii list will have the value:

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

So far I got:

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

      

printing returns an error because ord expects a character but receives a string. Does anyone know how I can fix this to return the ascii value of each letter? Thankyou

+3


source to share


2 answers


Treat words as one long string (using nested-comp for example):

ascii = [ord(ch) for word in words for ch in word]
# [104, 101, 108, 108, 111, 119, 111, 114, 108, 100]

      

Equivalent:



ascii = []
for word in words:
    for ch in word:
        ascii.append(ord(ch))

      

If you want to do it as separate words, then you change your list-comp:

ascii = [[ord(ch) for ch in word] for word in words]
# [[104, 101, 108, 108, 111], [119, 111, 114, 108, 100]]

      

+1


source


Your loop is repeated in a list words

, which is a list string

. Now ord

is a function that will return the integer ordinal of a single character string. Thus, you need to iterate over the characters in the string.

words = ["hello", "world"]
ascii = []
for word in words:
    ascii.extend(ord(ch) for ch in word)

      



print ascii

give you,

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

      

+1


source







All Articles