ord() function in Python
Last Updated :
30 Jun, 2023
Python ord() function returns the Unicode code from a given character. This function accepts a string of unit length as an argument and returns the Unicode equivalence of the passed argument. In other words, given a string of length 1, the ord() function returns an integer representing the Unicode code point of the character when an argument is a Unicode object, or the value of the byte when the argument is an 8-bit string.
Example
Here, ord(‘a’) returns the integer 97, ord(‘€’) (Euro sign) returns 8364. This is the inverse of chr() for 8-bit strings and of unichr() for Unicode objects. If a Unicode argument is given and Python is built with UCS2 Unicode, then the character’s code point must be in the range [0..65535] inclusive.
Python3
print ( ord ( 'a' ))
print ( ord ( '€' ))
|
Python ord() Syntax
Syntax: ord(ch)
Parameter : ch – A unicode character
How does ord work in Python?
In this example, We are showing the ord() value of an integer, character, and unique character with ord() function in Python.
Python3
print ( ord ( '2' ))
print ( ord ( 'g' ))
print ( ord ( '&' ))
|
Output :
50
103
38
Note: If the string length is more than one, a TypeError will be raised. The syntax can be ord(“a”) or ord(‘a’), both will give the same results. The example is given below.
Demonstration of Python ord() function
This code shows that ord() value of “A”, ‘A’ gives the same result.
Python
value = ord ( "A" )
value1 = ord ( 'A' )
print (value, value1)
|
Output
65 65
Error Condition while Using Ord(0)
A TypeError is raised when the length of the string is not equal to 1 as shown below.
Python3
value1 = ord ( 'AB' )
print (value1)
|
Output
Traceback (most recent call last):
File “/home/f988dfe667cdc9a8e5658464c87ccd18.py”, line 6, in
value1 = ord(‘AB’)
TypeError: ord() expected a character, but string of length 2 found
Python ord() and chr() Functions
The chr() method returns a string representing a character whose Unicode code point is an integer.
Syntax: chr(num)
num : integer value
Where ord() methods work on the Unicodeopposite for chr() function.
Example of ord() and chr() functions
This code print() the Unicode of the character with the ord() and after getting the Unicode we are printing the character with the chr() function.
Python3
value = ord ( "A" )
print (value)
print ( chr (value))
|
Output
65
A
Please Login to comment...