Python chr() function is your translator from numbers to characters. Give it a Unicode code point (an integer representing a character), and it gives you back the actual character that corresponds to that code.
chr()
Syntax
character = chr(code_point)
character
: A variable to store the resulting character.chr()
: The built-in Python function for the conversion.code_point
: An integer representing the Unicode code point of the desired character.
Example 1: Python chr()
result = chr(65)
print(result)
Code Explanation
- Line 1: Calls
chr()
with 65, the Unicode code point for the uppercase letter ‘A’. - Line 2: Prints the character ‘A’.
Output
A
Example 2: Python chr()
with Integer Numbers
result = chr(97)
print(result)
Code Explanation
- Line 1: Uses 97, the code point for lowercase ‘a’.
- Line 2: Prints ‘a’.
Output
a
Example 3: Python chr()
with Out of Range Integer
try:
result = chr(1114112) # Outside the valid Unicode range
except ValueError:
print("ValueError: chr() arg not in range(0x110000)")
Code Explanation
- Tries to use a code point beyond the valid range (0 to 0x10FFFF).
- Triggers a
ValueError
because it’s invalid. - Prints the error message.
Example 4: Python chr()
with Non-Integer Arguments
try:
result = chr("65") # String instead of an integer
except TypeError:
print("TypeError: an integer is required (got type str)")
Code Explanation
- Tries to pass a string to
chr()
, which expects an integer. - Raises a
TypeError
due to the incorrect argument type. - Prints the error message.
Example 5: Python chr()
with Special Character
result = chr(9829) # Unicode for a heart symbol
print(result)
Code Explanation
- Line 1: Uses the code point for a heart symbol.
- Line 2: Prints the heart symbol.
Output
♥