String to ASCII Conversion
Code
text="Hello there, How are you?" print([{char:ord(char)} for char in text])
Output: [{'H': 72}, {'e': 101}, {'l': 108}, {'l': 108}, {'o': 111}, {' ': 32}, {'t': 116}, {'h': 104}, {'e': 101}, {'r': 114}, {'e': 101}, {',': 44}, {' ': 32}, {'H': 72}, {'o': 111}, {'w': 119}, {' ': 32}, {'a': 97}, {'r': 114}, {'e': 101}, {' ': 32}, {'y': 121}, {'o': 111}, {'u': 117}, {'?': 63}]
It print all ASCII code for character in string.
ASCII to String Conversion
so chr() function is used to convert ASCII code to String
print('The character value of 98:',chr(98)) print('The character value of 99:',chr(99))
Output: The character value of 98: b The character value of 99: c
Now convert back the ascii code to string:
text="Hello there, How are you?" ascii_=[ord(char) for char in text] print([chr(asc) for asc in ascii_])
['H', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e', ',', ' ', 'H', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u', '?']
We can use the βjoinβ function to convert the list into string and get back our sentence in proper form
ascii_=[ord(char) for char in text] print(''.join([chr(asc) for asc in ascii_]))
Hello there, How are you?
Top comments (0)