user2747367
user2747367

Reputation: 143

Python: changing string values in lists into ascii values

I'm trying to convert characters in a string into individual ascii values. I can't seem to get each individual character to change into its relative ascii value.

For example, if variable words has the value ["hello", "world"], after running the completed code the list ascii would have the value :

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

So far I've got:

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

printing this returns an error as ord expect a character but gets a string. Does anyone know how i can fix this to return the ascii value of each letter? thankyou

Upvotes: 3

Views: 8408

Answers (2)

salmanwahed
salmanwahed

Reputation: 9647

Your loop iterates over the words list which is a list of string. Now, ord is a function that will return the integer ordinal of a one-character string. So you need the iterate over the characters of the string also.

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

print ascii will give you,

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

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142156

Treat words as one long string instead (using a nested list-comp for instance):

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

Equivalent to:

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

If you wanted to do them 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]]

Upvotes: 3

Related Questions