1.

How are Python’s built-in functions ord() and chr() related?

Answer»

These two functions have exactly the opposite behaviour to each other. The chr() function returns a string representing a CHARACTER to an integer argument which is a Unicode code point.

>>> chr(65) 'A' >>> chr(51) '3' >>> chr(546) 'Ȣ' >>> chr(8364) '€'

The chr() function returns corresponding CHARACTERS for integers between 0 to 1114111 (0x110000). For a number outside this range, PYTHON raises ValuError.

>>> chr(-10)    chr(-10) ValueError: chr() arg not in range(0x110000)

On the other hand ord() function returns an integer corresponding to Unicode code point of a character.

>>> ord('A') 65 >>> ord('a') 97 >>> ord('\u0222') 546 >>> ord('€') 8364

Note that ord() function accepts a string of only one character otherwise it raises TypeError as shown below:

>>> ord('aaa')    ord('aaa') TypeError: ord() EXPECTED a character, but string of length 3 found

These two functions are the inverse of each other as can be seen from the following

>>> ord(chr(65)) 65 >>> chr(ord('A')) 'A'


Discussion

No Comment Found