Python program to convert a character to ASCII code and vice versa
2 minsASCII stands for American Standard Code for Information Exchange. It is a character encoding standard that works with a set of 128 characters and represents them using 7-bit integers.
The ASCII character set includes Alphabets (A-za-z
), digits (0-9
), special characters ([{}]%@
), and control characters (\r
, \n
). ASCII represents these characters using integers. You can check out the complete ASCII table here.
In this article, you’ll learn how to convert (encode) a character to ASCII code and vice versa in Python.
Convert character to ASCII code in Python
You can get the ASCII value of a character in Python using the ord()
function:
>>> c = 'Z'
>>> ord(c)
90
Convert ASCII code to character in Python
To get the character associated with an ASCII code, you can use the chr()
function:
>>> ascii = 82
>>> chr(ascii)
'R'
Convert a string to a list of ASCII values in Python
The following program uses list comprehension to convert a string to a list of ASCII values:
>>> s = 'Python'
>>> [ord(c) for c in s]
[80, 121, 116, 104, 111, 110]
Convert a list of ASCII values to a string in Python
The following program shows you how to convert a list of ASCII values to a string:
>>> asciiValues = [72, 101, 108, 108, 111]
>>> characters = [chr(ascii) for ascii in asciiValues]
>>> ''.join(characters)
'Hello'