What is the use of the "ord" function in Python?

In Python, the ord() function is a built-in function used to return the Unicode code point of a specified character. It takes a single character as input and returns an integer representing its Unicode code point.

The general syntax of the ord() function is as follows:

  • character: The character for which you want to retrieve the Unicode code point.

Here's an example to demonstrate the usage of the ord() function:

char = 'A'
unicode_code_point = ord(char)

print(unicode_code_point)  # Output: 65

In this example, the ord() function is used to obtain the Unicode code point of the character 'A'. The resulting unicode_code_point is 65, which corresponds to the Unicode code point of the uppercase letter 'A' according to the ASCII encoding.

The ord() function is primarily useful when you need to work with Unicode characters and their corresponding code points. It allows you to convert characters to their numeric representations, which can be used for various purposes such as comparison, manipulation, or encoding.

Conversely, if you want to convert a Unicode code point back to its corresponding character, you can use the chr() function. Here's an example:

unicode_code_point = 65
character = chr(unicode_code_point)

print(character)  # Output: 'A'

In this example, the chr() function is used to convert the Unicode code point 65 back to the corresponding character, which is 'A'.

It's important to note that the ord() function only accepts a single character as input. If you pass a string with multiple characters, it will raise a TypeError. Additionally, the ord() function returns the Unicode code point of the first character in the input string, if a string is provided.

Overall, the ord() function provides a convenient way to retrieve the Unicode code point of a character, which is useful when working with Unicode data or performing character-level operations.

Related Questions You Might Be Interested