Python chr() method is used to get a string representing a character that points to a Unicode code integer.
Python chr
Python chr() is a built-in method that returns the character (a string) from an integer representing the character’s Unicode code point. The chr() function takes an integer as an argument and returns a string representing a character at that code point. The chr() method returns a string representing a character whose Unicode code point is an integer.
Syntax
chr(i)
Arguments
If the integer i is outside the range, ValueError will be raised.
The chr() function takes only one integer as a parameter.
The range may vary from 0 to 1,1141,111(0x10FFFF in base 16).
Return value
The chr() method returns the character whose Unicode point is num, an integer.
Example
See the following code example.
numbers = [99, 38, 98] for number in numbers: print("Character of ASCII value", number, "is ", chr(number))
See the following output.
➜ pyt python3 app.py Character of ASCII value 99 is c Character of ASCII value 38 is & Character of ASCII value 98 is b ➜ pyt
Okay, now let’s give some input that is out of the range.
data = -1 print(chr(data))
See the following output.
➜ pyt python3 app.py Traceback (most recent call last): File "app.py", line 2, in <module> print(chr(data)) ValueError: chr() arg not in range(0x110000) ➜ pyt
The chr() function returns the character that represents the specified Unicode.
Sometimes we need to convert an ASCII character to its corresponding character, and for such cases Python chr() function is used.
Python ord
Python ord() and chr() functions are exactly opposite of each other.
Python ord() function takes a string argument of a single Unicode character and returns its integer Unicode code point value.
See the following code.
# app.py print(ord('Ǵ')) print(ord('ɘ')) print(ord('ʼ'))
See the following output.
➜ pyt python3 app.py 500 600 700 ➜ pyt
That means, it will give us the integer value, which is opposite returning the Unicode character value.
That’s it for this tutorial.