Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 420
user2747367 Avatar asked Jun 25 '26 05:06

user2747367


1 Answers

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]]
like image 77
Jon Clements Avatar answered Jun 28 '26 03:06

Jon Clements



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!