Python ord()


Python ord() is a built-in function that returns an integer of a given single Unicode character. ord() is the short form for ordinal. The returned integer represents the Unicode code point.

python ord() function

Python ord() Syntax

ord(c)

The ord() method takes a single parameter as argument.

  • c (required) – character of length 1 whose Unicode point is to be found

Python ord() is the inverse of chr() for 8-bit strings and of unichr() for Unicode objects. If a Unicode argument is given then the character’s code point must be in the range 0 to 65535 otherwise, a TypeError will be raised as the length of string becomes two.

Python ord() Example

>>> #Unicode code point of an integer
>>> print("The Unicode code point for 1 = " ,ord('1'))
The Unicode code point for 1 =  49

>>> #Unicode code point of a character
>>> print("The Unicode code point for A = " ,ord('A'))
The Unicode code point for A =  65

As you can see in above example, Python ord() works for a single character. Now when we pass two characters as an argument to ord() function, a TypeError will be raised.

Here is the example.

>>> #ord() function for multiple characters
>>> ord('XY')
File "<pyshell#9>", line 1, in <module>
 ord('XY')
TypeError: ord() expected a character, but string of length 2 found

Python ord() Example : Return Unicode code point value of a user input

py_var = input("Enter a character:")

py_codepoint = ord(py_var)

print("The Unicode code point of the character",py_var ,"=" ,py_codepoint)

Above program will yield following output.

Enter a character:#
The Unicode code point of the character # = 35