Kodeclik Blog

Python chr()

Ever wonder how Python stores characters internally? For instance, the character “A” is denoted by the integer “65”, the character “B” is denoted by “66”, and so on. These representations are known as ASCII representations (American Standard Code For Information Interchange) which are primarily aimed at letters, numbers, and a few special characters that you will find on your keyboard. chr() is a Python function to map the integer representation to the character it denotes. The chr() function is quite versatile and uses Unicode formats which can be viewed as a superset of ASCII.
Let us try the chr() function out. Consider the following code:
It prints:
Let us guess the encoding of Z. Encodings for consecutive characters are usually also consecutive. So the encoding for Z is likely to be: 65+26-1. Let us try:
This gives as expected:
Similarly, the unicode representation of ‘a’ is 97, so we can try:
This gives:
The input to the chr function is usually bounded and depends on your implementation, library, and other considerations. Consider trying chr() with a very large integer:
This outputs:
Thus Python is giving you feedback that the input to chr() can be a maximum of “0x110000” which is a hexadecimal number (note the 0x in front). Similarly, the smallest value of chr() can be 0. So if we try:
we will get the same error:
The above examples should highlight that we can also give inputs to chr() in hexadecimal notation. Since “65” in decimal is “41” in hexadecimal, we can do:
and obtain the same output as before:
You can print a smiley by using its unicode representation:
yielding the output:
Similarly a tennis ball is denoted by the unicode character “0x1F3BE” so the following code:
outputs a tennis ball.
Checkout https://unicode.org for a complete list of all unicode characters.
For some pictorial fun, try the following program to print unicode characters from a starting hexadecimal value to an ending value:
The output is:

The inverse of chr() is ord()

Just like chr() gives the character for a specific unicode value, ord() returns the unicode value for a given character. For instance, we can try:
and this will give:
Thus, if you do:
The output will be
In the above segment of code, if we replace 65 by any number, we will obtain the same value back. If we try:
we will get:
Thus ord() and chr() are inverses of each other. See also our blogpost on converting strings to bytes in Python.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.