In this tutorial, we will delve into one of Python’s built-in functions, the
ord() function. This function is a simple yet powerful tool in Python programming that can be used to convert a character into its corresponding Unicode integer.
What is the ord() Function?
ord() function in Python takes a string argument of a single Unicode character and returns its corresponding Unicode code point, which is an integer.
# Example print(ord('A')) # Output: 65 print(ord('$')) # Output: 36
This function is particularly useful when you need to work with characters’ ASCII values or manipulate text data at a more granular level.
Syntax of ord() Function
The syntax for using the
ord() function is straightforward:
Note that the ‘character’ must be a single Unicode character. If you try to pass more than one character or an empty string, Python will raise a TypeError.
A Practical Example of Using ord()
To illustrate how we can use the
ord() function in real-world scenarios, let’s consider an example where we want to encrypt a message by shifting each letter by two places. Here’s how we could do it:
def shift_characters(message): encrypted_message = "" for char in message: if char.isalpha(): unicode_value = ord(char) new_unicode_value = unicode_value + 2 new_character = chr(new_unicode_value) encrypted_message += new_character else: encrypted_message += char return encrypted_message print(shift_characters("Hello, World!")) # Output: "Jgnnq, Yqtnf!"
In this example, we used the
ord() function to get the Unicode value of each character and then added 2 to it. We then converted it back to a character using Python’s
ord() function is a simple yet powerful tool for working with Unicode characters. It allows you to convert any single character into its corresponding Unicode integer, enabling more granular control over text data manipulation.
We hope this tutorial has helped you understand how to use the
ord() function in Python effectively!