Python ord() Function



The Python ord() function is used to retrieve an integer representing the Unicode code point of a given character. Unicode code points are unique numbers assigned to each character in the Unicode standard, and they are non-negative integers ranging from 0 to 0x10FFFF (decimal 1114111).

The function can accept either a character or a string of length 1, allowing the parameter to accept both single quotes ('') and double quotes (""). Therefore, when you use the ord() function on a character, it informs you about the specific number representing that character in the Unicode standard.

For instance, using ord('A') would return 65, as 65 is the Unicode code point for the uppercase letter 'A'.

Syntax

Following is the syntax of python ord() function −

ord(ch)

Parameters

This function accepts a single character as its parameter.

Return Value

This function returns an integer representing the Unicode code point of the given character.

Example

Following is an example of the python ord() function. Here, we are retrieving the Unicode value of character "S" −

character = 'S'
unicode_value = ord(character)
print("The Unicode value of character S is:", unicode_value)

Output

Following is the output of the above code −

The Unicode value of character S is: 83

Example

Here, we are retrieving the Unicode value of a special character "*" using the ord() function −

character = '*'
unicode_value = ord(character)
print("The Unicode value of character * is:", unicode_value)

Output

The output obtained is as follows −

The Unicode value of character * is: 42

Example

In this example, we are taking two characters, "S" and "A," and finding their respective Unicode values, which are numerical representations of these characters. We then add these Unicode values together to retrieve the result −

character_one = "S"
character_two = "A"
unicode_value_one = ord(character_one)
unicode_value_two = ord(character_two)
unicode_addition = unicode_value_one + unicode_value_two
print("The added Unicode value of characters S and A is:", unicode_addition)

Output

The result produced is as follows −

The added Unicode value of characters S and A is: 148

Example

If we pass a string of length more than 2 to the ord() function, it will raise a TypeError.

Here, we are passing "SA" to the ord() function to demonstrate the type error −

string = "SA"
unicode_value = ord(string)
print("The added Unicode value of string SA is:", unicode_value)

Output

We can see in the output that we get a TypeError because we have passed a string with length greater than 1 −

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
    unicode_value = ord(string)
TypeError: ord() expected a character, but string of length 2 found
python-ord-function.htm
Advertisements