ord() in Python

Video Tutorial
FREE
ord & chr in Python thumbnail
This video belongs to
Python Course for Beginners With Certification: Mastering the Essentials
16 modules
Certificate
Topics Covered

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 ord() in python

The Syntax of the ord() is as follows:

Parameter Value of ord() in python

The function can only take one parameter,

  • character, whose Unicode value is desired.

Return Value of ord() in python

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 is utilized to retrieve the Unicode code point of a single character. It accepts a single-character string as input and produces an integer representing the Unicode code point of that character. If the input string's length is not exactly 1, the ord() function raises a TypeError.

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.

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

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

Python ord() and chr() Functions

The chr() method returns a string representing a character whose Unicode code point is an integer.

Syntax: chr(num), where num is integer value

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.