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:
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:
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:
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:
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.