How to Use the Python ord() Function

09/13/2021

Contents

In this article, you will learn how to use the Python ord() function.

Python ord() Function

In Python, the ord() function is used to get the integer Unicode code point of a given Unicode character. Here’s how you can use the ord() function in Python:

  1. First, choose the Unicode character for which you want to get the code point. You can use a single character or a string of characters.
  2. Call the ord() function and pass in the character as an argument. For example:

    >>> ord('A')
    65
    

In this example, the ord() function returns the integer value of the Unicode code point for the character “A”, which is 65.

Note that the ord() function only accepts a single character as input. If you pass a string with multiple characters, you will get a TypeError.

>>> ord('hello')
Traceback (most recent call last):
  File "", line 1, in 
TypeError: ord() expected a character, but string of length 5 found

In this example, the ord() function raises a TypeError because it expects a single character but receives a string of length 5.

That’s how you can use the ord() function in Python to get the integer Unicode code point of a given Unicode character.

 

Here are a few more things you should know about the ord() function in Python:

  • The ord() function is a built-in function in Python, which means you don’t need to import any module to use it.
  • The ord() function can be used to get the Unicode code point of any Unicode character, including non-Latin characters.
  • The ord() function can also be used with escape sequences, such as \n, to get the Unicode code point of special characters. For example:

    >>> ord('\n')
    10
    

    In this example, the ord() function returns the integer value of the Unicode code point for the newline character, which is 10.

  • The ord() function can be used in conjunction with the chr() function to convert between Unicode code points and their corresponding characters. For example:

    >>> chr(65)
    'A'
    >>> ord('A')
    65
    

    In this example, the chr() function takes the integer value of the Unicode code point for the character “A” and returns the corresponding character. The ord() function does the opposite: it takes the character “A” and returns the integer value of its Unicode code point.