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
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With