How to Use chr and ord Functions in Python
In Python,
chr() converts a Unicode code point (an integer) to its corresponding character, while ord() converts a single character to its Unicode code point (an integer). Use chr() when you want a character from a number, and ord() when you want the number representing a character.Syntax
chr() takes one integer argument and returns the character for that Unicode code point.
ord() takes one character (string of length 1) and returns its Unicode code point as an integer.
python
chr(i) ord(c)
Example
This example shows how to convert a number to a character using chr() and how to get the number for a character using ord().
python
number = 65 character = chr(number) print(f"chr({number}) = {character}") char = 'A' code_point = ord(char) print(f"ord('{char}') = {code_point}")
Output
chr(65) = A
ord('A') = 65
Common Pitfalls
- Passing a number outside the valid Unicode range (0 to 0x10FFFF) to
chr()causes aValueError. - Passing a string longer than one character to
ord()causes aTypeError. - Remember that
ord()only accepts a single character string, not empty or multiple characters.
python
try: print(chr(1114112)) # Invalid code point except ValueError as e: print(f"Error: {e}") try: print(ord('AB')) # More than one character except TypeError as e: print(f"Error: {e}")
Output
Error: chr() arg not in range(0x110000)
Error: ord() expected a character, but string of length 2 found
Quick Reference
| Function | Input | Output | Description |
|---|---|---|---|
| chr() | Integer (Unicode code point) | Character (string) | Convert number to character |
| ord() | Single character (string) | Integer (Unicode code point) | Convert character to number |
Key Takeaways
Use chr() to get a character from a Unicode code point number.
Use ord() to get the Unicode code point number from a single character.
chr() input must be between 0 and 0x10FFFF; ord() input must be a single character string.
Passing invalid inputs to chr() or ord() raises errors you should handle.
These functions help convert between characters and their numeric Unicode values easily.