Python ord() Function

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Video Tutorial

ord & chr in Python

Overview

The ord() function in Python is a method that converts a character to its Unicode. The Unicode Standard provides a unique number for every character, no matter what platform, device, application or language.

Syntax of Python ord()

The Syntax of the ord() is as follows:

Parameter Value of Python ord()

The function can only take one parameter,

  • character, whose Unicode value is desired.

Return Value of Python ord()

Return Type: int

The function returns an integer value which is equivalent to the Unicode value of the provided character.

Python ord() Example

Output

What is ord() Function in Python?

The ord() function in Python accepts a single character as an argument and returns an integer value representing the Unicode equivalent of that character. The ord function is short of the ordinal which means a number.

The Unicode is an internationally recognized character encoding system. Unicode is at the heart of all software. You're currently utilizing Unicode, whether you recognize it or not! “Computers only deal with binary numbers,” as the saying goes. They keep track of letters and other characters by assigning each one a number. There were hundreds of different encoding schemes for allocating these numbers before Unicode was developed.

What happens if you don’t use a standard encoding? Let’s say that we are using legacy encoding, then our fonts might clash with the fonts of someone else somewhere. We might have a Ű in our font while someone else has Ɛ in the same place in this case our files will become incompatible. Now, because Unicode assigns a unique number to each character, you won't have this difficulty if you utilize it.

If your document specifies U+0289, any computer software will know exactly what character to use.

What is Unicode

So now we are using a standard encoding format but how do we know what character is what?
We map every character to some value. Sometimes we require this value and for that, we have to use the ord function in Python.

More Examples

Example 1: Python Program to Print the Unicode Value of Every Character in a String

Output

Example 2: Python Program to Find the Unicode Value of the Digit

It turns out that the digit 0 does not have the Unicode value of 0, so what is it's and other digit’s Unicode value?

Output

Example 3: What Happens If We Pass More Than One Character in the ord() Function?

The ord function takes only one character as input, Here's what will happen if we pass an input whose size is greater than 1.

Output

Conclusion

  • Unicode is an international standard for character encoding.
  • ord() in Python is a built-in function that helps retrieve the Unicode value of a character.
    • It takes a character as input.
    • It returns an integer value corresponding to the character.