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:
ord(character)
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:
# Get the character from the user
char = input("Enter a single character: ")
# Check if the user entered a single character
if len(char) == 1:
ascii_value = ord(char)
print(f"The ASCII value of the character '{char}' is: {ascii_value}")
else:
print("Please enter a single 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:
chr(ascii_value)
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:
# Get the ASCII value from the user
ascii_value = int(input("Enter an ASCII value (0-127): "))
# Check if the value is in the ASCII range
if 0 <= ascii_value <= 127:
char = chr(ascii_value)
print(f"The character corresponding to the ASCII value {ascii_value} is: '{char}'")
else:
print("Please enter a valid ASCII value between 0 and 127.")
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.