chr() function converts an integer to its unicode character and returns it.
The syntax of
chr() function is:
chr() function takes in a single parameter num which is an integer in the range 0 to 1,114,111. It can return the following:
- unicode character of the corresponding integer if the integer value is in the range
- ValueError, in the case integer value is out of range
- TypeError, in the case a non-integer argument is passed
You can see the unicode representation of different characters here.
Let us pass integer arguments in the correct range.
num1 = 65 print(chr(num1)) num2 = 120 print(chr(num2))
In the above example, we have passed integers to the
chr() function, and it returns the corresponding unicode characters.
Let us again pass integer arguments but this time, the values will be out of range.
num = -65 print(chr(num))
ValueError: chr() arg not in range(0x110000)
In the above example, we passed -65 as the argument, which is out of range, and hence it throws the ValueError.
Let us now pass something other than integer as the argument to the
TypeError: an integer is required (got type str)
As the error itself tells, an integer is required but we have passed string.
In this part, we learned about the Python
chr() function with the help of examples.
If you liked this post, you can consider subscribing to my newsletter.