Using ord()
and chr()
Functions in Python
In Python, the ord()
and chr()
functions are used to work with ASCII and Unicode values. The ord()
function converts a single character into its Unicode (or ASCII) integer representation, while the chr()
function converts an integer back into its corresponding character.
1. ord()
Function
The ord()
function takes a single character (a string of length 1) and returns its Unicode code point (an integer). This is useful when you need to know the ASCII or Unicode value of a specific character.
Code Example for ord()
Function
# Using ord() function to get the Unicode of a character
char = 'A'
unicode_value = ord(char)
print("Unicode value of 'A':", unicode_value)
Output
Explanation
The character 'A'
has a Unicode value of 65
. Using ord('A')
returns 65
.
2. chr()
Function
The chr()
function takes an integer (Unicode code point) and returns the character that corresponds to that code point. This function is useful when you have an integer and want to know the character it represents.
Code Example for chr()
Function
# Using chr() function to get the character for a Unicode value
unicode_value = 97
character = chr(unicode_value)
print("Character for Unicode 97:", character)
Output
Explanation
The Unicode value 97
corresponds to the character 'a'
. Using chr(97)
returns 'a'
.
Examples of Using ord()
and chr()
Together
Example: Generating a Range of Alphabet Letters
You can use a combination of ord()
and chr()
to generate a list of alphabet letters.
Code Example
# Generating letters from 'A' to 'Z' using ord() and chr()
alphabet = [chr(i) for i in range(ord('A'), ord('Z') + 1)]
print("Alphabet letters:", alphabet)
Output
Explanation
In this example, ord('A')
gives the starting integer value for 'A' (65), and ord('Z')
provides the value for 'Z' (90). We use chr()
to convert these Unicode values back to characters.
Example: Checking if a Character is Uppercase or Lowercase
You can use ord()
to check if a character is uppercase or lowercase based on its Unicode value.
Code Example
# Check if a character is uppercase or lowercase using ord()
char = 'g'
if ord('A') <= ord(char) <= ord('Z'):
print(char, "is uppercase.")
elif ord('a') <= ord(char) <= ord('z'):
print(char, "is lowercase.")
Output
Explanation
In this example, the program checks if the Unicode value of char
falls within the range of uppercase letters (A-Z) or lowercase letters (a-z).
Conclusion
The ord()
and chr()
functions are fundamental tools for converting between characters and their Unicode or ASCII values. They are particularly useful in scenarios where you need to manipulate characters at a low level, such as generating letter ranges, working with Unicode values, or verifying the case of letters.