Python chr()
Function
The chr() function in Python returns the character that represents the specified Unicode code point (an integer). It’s the opposite of ord()
, which gives the Unicode number for a character.
Syntax
chr(i)
Parameters:
i
– An integer representing the Unicode code point (between 0 and 1,114,111)
Returns:
- The string representing the character whose Unicode code point is
i
Example 1: Basic Usage
print(chr(65))
A
This is because the Unicode code point 65
maps to the character 'A'
.
Example 2: Lowercase Letter
print(chr(97))
a
Example 3: Symbols and Special Characters
print(chr(36)) # Dollar sign
print(chr(8364)) # Euro sign
$
€
Example 4: Creating Alphabets Using chr()
for i in range(65, 91):
print(chr(i), end=" ")
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Use Case: Why Use chr()
?
- To generate characters programmatically
- Useful in ASCII/Unicode manipulation tasks
- Often used in algorithms and encryption tasks (like Caesar cipher)
Common Mistakes
- Out of range: Passing a number below 0 or above 1,114,111 will raise a
ValueError
- Non-integer: Passing a float or string will raise a
TypeError
Interview Tip
The chr()
and ord()
functions often appear together in string manipulation or encryption interview problems.
Summary
chr(i)
converts a Unicode code point to a character- Only accepts integers between 0 and 1,114,111
- Opposite of
ord()
, which converts a character to a number
Practice Problem
Write a Python program to print all characters from Unicode 97 to 122 on one line (a to z).
for i in range(97, 123):
print(chr(i), end=" ")