ASCII, which stands for the American Standard Code for Information Interchange, is a character encoding standard that represents each character as a number between 0 and 127. Each number corresponds to a unique character. For instance, the ASCII value of the character ‘A’ is 65, and that of ‘a’ is 97.
In Python, finding the ASCII value of a character is a straightforward task, thanks to the built-in function ord(). This article explores how to retrieve the ASCII value of a character using this function.
The ord() function
Python’s built-in ord() function returns an integer representing the Unicode code point of the given Unicode character. For ASCII characters, this code point is the same as its ASCII value.
Syntax:
Where character is a single Unicode character string.
Return Value: This function returns an integer representing the Unicode code point of the given Unicode character.
Example: Finding the ASCII value of a character
Here’s a simple program to retrieve the ASCII value of a character:
When you run the above program and input the character ‘A’, the output will be:
Output:The ASCII value of the character 'A' is: 65
Bonus: Convert ASCII Value to Character
In the same way you might want to find the ASCII value of a character, you might also want to convert an ASCII value back to its corresponding character. For this, you can use Python’s chr() function.
Syntax:
Where ascii_value is an integer representing the ASCII value.
Return Value: This function returns a string representing a character whose Unicode code point is the given integer.
Here’s a simple example:
If you run the program and input the value 65, the output will be:
Output:The character corresponding to the ASCII value 65 is: 'A'
Conclusion
Python offers straightforward mechanisms to work with ASCII values through the ord() and chr() functions. Whether you're looking to find the ASCII value of a character or retrieve a character from its ASCII value, these functions make the task simple and intuitive.