ord() and chr() Function in Python.

In Python, the ord() and chr() functions are essential tools for working with Unicode, they allow you to convert an integer to Unicode and Unicode to an integer respectively. Let's dive deeper into these functions.


What is Unicode?

Unicode is a standardized character encoding system that assigns a unique number, known as a code point, to every character in almost every script and language in the world. It is designed to be a universal character set, encompassing characters from different writing systems. For example, 'A' is assigned the code point 65, and '❤' is assigned the code point 2764.


What is ord() in Python?

The ord() function in Python is a built-in function that returns an integer representing the Unicode character. It stands for "ordinal," and its primary use is to obtain the Unicode code point of a given character.

Syntax:

ord(character)

Python Code:
# Using ord() to get the Unicode code point of a character

unicode_value = ord('A')

print(f"The Unicode code point of 'A' is {unicode_value}")
Output:
The Unicode code point of 'A' is 65

In this example, ord('A') returns 65, which is the Unicode code point for the character 'A'.

What is chr() in Python?

In Python, chr() is a built-in function that converts an integer representing a Unicode code point into the corresponding character. The name chr stands for "character." This function is the inverse of the ord() function, which converts a character to its Unicode code point.

Syntax: 
# i is an integer representing an integer point
chr(i)

Python Code:
# Using chr() to convert a Unicode code point to a character
unicode_code_point = 65  # Unicode code point for 'A'
character = chr(unicode_code_point)

# Printing the result
print(f"The character to the Unicode code point {unicode_code_point} is: {character}")

In this example, chr(65) returns the character 'A' because 65 is the Unicode code point for the uppercase letter 'A.'

In this article, we have discussed ord() and chr() functions which help us in working with Unicode. It is an important concept to learn for solving many real-life coding problems.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS