Tutorial Study Image

Python ord()

The built-in function ord() is used to convert given Unicode characters to an integer representation. It is an inverse function of chr() here it converts integer value to the character. 


ord(ch) #where ch is a unicode character 
 

ord() Parameters:

Takes only one parameter. The integer value should be in the range from 0 through 1,114,111 (0x10FFFF in hexadecimal format). If the input integer is out of this range a ValueError will be raised.

Parameter Description Required / Optional
ch  a Unicode character Required

ord() Return Value

If we passed a string whose length is more than one, a TypeError will be raised.

Input Return Value
 Unicode character Integer value

Examples of ord() method in Python

Example 1: How ord() works in Python?


print(ord('5'))    # 53
print(ord('A'))    # 65
print(ord('$'))    # 36
 

Output:

53
65
36

Example 2: ValueError case in ord()


start = 0
end = 1114111
 
try:
    for i in range(start, end+2):
        a = chr(i)
except ValueError:
    print("ValueError for i =", i)
 

Output:

ValueError for i = 1114112

Example 3: TypeError case in ord()


y = ord('Hi')
 

Output:

TypeError: ord() expected a character, but string of length 2 found