chr()
The built-in chr()
function returns the character whose Unicode code point is the integer provided as an argument:
>>> chr(65)
'A'
chr()
Signature
chr(i)
Arguments
Argument | Description |
---|---|
i |
An integer representing a valid Unicode code point. |
Return Value
- Returns a string that represents the character associated with the given Unicode code point.
chr()
Examples
With an integer representing an uppercase letter as an argument:
>>> chr(90)
'Z'
With an integer representing a lowercase letter as an argument:
>>> chr(120)
'x'
With an integer representing a special character as an argument:
>>> chr(38)
'&'
chr()
Common Use Cases
The most common use cases for the chr()
function include:
- Converting numerical Unicode code points to their corresponding characters
- Generating characters for data encoding and decoding tasks
- Creating characters dynamically in loops or comprehensions
chr()
Real-World Example
Suppose you want to generate a list of all uppercase English letters using their Unicode code points. You can use the chr()
function to accomplish this:
>>> [chr(i) for i in range(65, 91)]
[
'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'
]
In this example, chr()
is used in a list comprehension to generate each uppercase letter by iterating over their respective code points.
Related Resources
Tutorial
Unicode & Character Encodings in Python: A Painless Guide
In this tutorial, you'll get a Python-centric introduction to character encodings and unicode. Handling character encodings and numbering systems can at times seem painful and complicated, but this guide is here to help with easy-to-follow Python examples.
For additional information on related topics, take a look at the following resources:
- Strings and Character Data in Python (Tutorial)
- Unicode in Python: Working With Character Encodings (Course)
- Strings and Character Data in Python (Course)
- Python Strings and Character Data (Quiz)