Inversely, the Python chr() function takes a Unicode code point (integer) and returns a string.
See the section below for learning how to use the ord() and chr() functions with examples.
An example of using Python ord() function
In this simple example, the code point of the letter ‘B’ is returned by using the ord() function.
# An example of ord() function print("The Unicode code point for B = " ,ord('B'))
Output:
The code points of numbers 0-9 by using range example
In the following example, a range of 10 numbers (0-9) is created.
A for loop is used to iterate through the range.
The ord Python function is used to display the code point of each number in the range.
#Know Unicode code points of numbers by ord() function for x in range(10): print ("The Unicode code point of",x ,'=' ,ord(str(x)))
Output:
As range items are numbers, so it will produce an error if directly used in the ord() function.
As such, ord() takes a string, so str() function is used to convert the number into the string.
A user entered character example
For this example, the character is taken from the user by using the input function.Enter a single character and ord() function will return the Unicode code point of that character.
Have a look:
str_ord = input("Enter a character?") cde_pt = ord(str_ord) print("The Unicode code point of the character",str_ord ,"=" ,cde_pt)
Sample Outputs:
The chr() function example
In this example, different codes are given in the chr() function, and its returned values are displayed:
#A demo of using chr() function print("Unicode code point 65 = ", chr(65)) print("Unicode code point 36 = ", chr(36)) print("Unicode code point 36 = ", chr(163)) print("Unicode code point 36 = ", chr(38)) print("Unicode code point 1114112 = ", chr(1114112))
The chr() function has a certain range which is 0 through 1,114,111 (0x10FFFF in base 16).
If you enter a value which is out of the range, an error (ValueError) occurs as shown in the last part of this example.
An example of using range with chr()
this is the inverse of the example that we used with Python range and ord() function.
This time, a range is created between 65 – 80 numbers that are used as the argument in the chr() function as follows:
for x in range(65,80,1): print ("code point",x ,'=' ,chr(x))
Result:
code point 66 = B
code point 67 = C
code point 68 = D
code point 69 = E
code point 70 = F
code point 71 = G
code point 72 = H
code point 73 = I
code point 74 = J
code point 75 = K
code point 76 = L
code point 77 = M
code point 78 = N
code point 79 = O
You can see, the characters from A-O are displayed.