Python ord() Function

The ord() function in Python is used to convert a single character to its corresponding Unicode code point. This function is particularly useful when you need to work with character encodings or perform operations based on the numerical values of characters.

Table of Contents

  1. Introduction
  2. ord() Function Syntax
  3. Understanding ord()
  4. Examples
    • Basic Usage
    • Converting a List of Characters
  5. Real-World Use Case
  6. Conclusion

Introduction

The ord() function converts a single character (a string of length 1) to its Unicode code point, which is an integer. This is useful in various scenarios, such as encoding/decoding characters, processing text, and implementing algorithms that require character comparisons or transformations.

ord() Function Syntax

The syntax for the ord() function is as follows:

ord(c)

Parameters:

  • c: A single character (a string of length 1).

Returns:

  • An integer representing the Unicode code point of the character.

Raises:

  • TypeError: If the input is not a single character.

Understanding ord()

The ord() function takes a single character and returns its Unicode code point. Unicode is a universal character encoding standard that assigns a unique number to every character, regardless of platform, program, or language.

Examples

Basic Usage

To demonstrate the basic usage of ord(), we will convert a single character to its Unicode code point.

Example

# Converting a single character to its Unicode code point
char = 'A'
code_point = ord(char)
print(f"Unicode code point of '{char}':", code_point)

Output:

Unicode code point of 'A': 65

Converting a List of Characters

This example shows how to convert a list of characters to their corresponding Unicode code points.

Example

# List of characters
chars = ['A', 'B', 'C', 'a', 'b', 'c']

# Converting each character to its Unicode code point
code_points = [ord(char) for char in chars]
print("Unicode code points:", code_points)

Output:

Unicode code points: [65, 66, 67, 97, 98, 99]

Real-World Use Case

Processing Text and Encoding

In real-world applications, the ord() function can be used for text processing and encoding, such as implementing custom encoding schemes or processing text based on character values.

Example

# Encrypting a message using a simple Caesar cipher
def encrypt(message, shift):
    encrypted_message = ''
    for char in message:
        if char.isalpha():
            shifted_code_point = ord(char) + shift
            if char.islower():
                base = ord('a')
                encrypted_message += chr((shifted_code_point - base) % 26 + base)
            else:
                base = ord('A')
                encrypted_message += chr((shifted_code_point - base) % 26 + base)
        else:
            encrypted_message += char
    return encrypted_message

message = "Hello, World!"
shift = 3
encrypted_message = encrypt(message, shift)
print("Original message:", message)
print("Encrypted message:", encrypted_message)

Output:

Original message: Hello, World!
Encrypted message: Khoor, Zruog!

Validating and Processing User Input

The ord() function can also be used to validate and process user input, such as ensuring that input contains only valid characters or transforming input based on character values.

Example

# Validating if a string contains only ASCII characters
def is_ascii(s):
    return all(ord(char) < 128 for char in s)

input_string = "Hello123"
print("Is ASCII:", is_ascii(input_string))  # True

input_string = "Hello😊"
print("Is ASCII:", is_ascii(input_string))  # False

Output:

Is ASCII: True
Is ASCII: False

Conclusion

The ord() function in Python is used for converting single characters to their Unicode code points. By using this function, you can perform operations based on the numerical values of characters, process text efficiently, and implement custom encoding schemes. This function is particularly helpful in scenarios such as text processing, encoding/decoding characters, and validating user input in your Python applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top