Python ord()
The ord() function is a built-in Python function that converts a Unicode character to its corresponding integer Unicode code point value. It essentially performs the opposite operation of the chr() function, which converts an integer to its Unicode character.
When working with text processing, character encoding, or data conversion, the ord() function serves as an essential tool. It allows programmers to work with the numerical representation of characters, which is helpful for various applications such as encryption algorithms, character manipulation, and data validation.
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 CoursesIncludes 6 Courses
- With Professional CertificationWith Professional Certification
- Beginner Friendly.75 hours75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With CertificateWith Certificate
- Beginner Friendly.24 hours24 hours
Syntax
ord(character)
Parameters:
character: A Unicode character (string of length 1). If the string contains more than one character, aTypeErroris raised.
Return value:
The ord() function returns an integer that represents the Unicode code point for the given character.
Example 1: Basic Usage of ord()
This example demonstrates how to get the Unicode value of basic characters:
# Get Unicode value of uppercase letterprint(ord('A'))# Get Unicode value of lowercase letterprint(ord('a'))# Get Unicode value of a digitprint(ord('5'))# Get Unicode value of a special characterprint(ord('@'))Copy to clipboardCopy to clipboard
This example results in the following output:
65975364Copy to clipboardCopy to clipboard
The ASCII values for βAβ, βaβ, β5β, and β@β are 65, 97, 53, and 64 respectively. These values are part of the Unicode standard which includes ASCII as its first 128 characters.
Example 2: Working with Non-ASCII Characters
This example shows how ord() handles characters beyond the ASCII range, including symbols and characters from different languages:
# Unicode for emoji (smiling face)print(ord('π'))# Unicode for Chinese character (means "center")print(ord('δΈ'))# Unicode for Russian character (Cyrillic letter)print(ord('Π―'))# Unicode for Euro symbolprint(ord('β¬'))Copy to clipboardCopy to clipboard
This example results in the following output:
1285122001310718364Copy to clipboardCopy to clipboard
As shown, the ord() function can handle characters from any language or symbol set in the Unicode standard, returning their unique numerical code points.
Codebyte Example: Character Manipulation with ord()
This example demonstrates a practical application of the ord() function in a Caesar cipher implementation, which is a basic encryption technique:
defcaesar_encrypt(text, shift):"""Encrypts a text using the Caesar cipher technique.Args:text: The text to encryptshift: The number of positions to shift each letterReturns:The encrypted text"""result =""for char in text:# Check if character is a letterif char.isalpha():# Get the Unicode valuechar_code =ord(char)# Determine if it's uppercase or lowercasebase =ord('A')if char.isupper()elseord('a')# Apply the shift (modulo 26 to wrap around the alphabet)shifted_code =(char_code - base + shift)%26+ base# Convert back to a characterresult +=chr(shifted_code)else:# Keep non-alphabetic characters unchangedresult += charreturn result# Example usageoriginal_text ="Hello, World!"shift_value =3encrypted_text = caesar_encrypt(original_text, shift_value)print(f"Original: {original_text}")print(f"Encrypted (shift {shift_value}): {encrypted_text}")Copy to clipboardCopy to clipboard
In this example, the ord() function converts each character to its Unicode value, apply a shift, and then convert back to a character using the chr() function. This demonstrates how ord() can be used in practical text transformation scenarios.
Frequently Asked Questions
1. What happens if I pass more than one character to ord()?
If you pass a string with more than one character to ord(), Python will raise a TypeError. The function is designed to work with exactly one character.
try:print(ord('AB'))except TypeError as e:print(f"Error: {e}")Copy to clipboardCopy to clipboard
The output for this code will be:
Error: ord() expected a character, but string of length 2 foundCopy to clipboardCopy to clipboard
2. What is the relationship between ord() and chr()?
The ord() and chr() functions are complementary. ord() converts a character to its corresponding Unicode code point, while chr() converts a Unicode code point to its character representation.
character ='A'code_point =ord(character)print(f"ord('{character}') = {code_point}")# Convert back using chr()same_character =chr(code_point)print(f"chr({code_point}) = '{same_character}'")Copy to clipboardCopy to clipboard
The output for this code will be:
ord('A') = 65chr(65) = 'A'Copy to clipboardCopy to clipboard
3. Can ord() handle characters from any language?
Yes, ord() can handle any character that is part of the Unicode standard, which contains characters from virtually all modern written languages, as well as many symbols and emojis.
All contributors
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 CoursesIncludes 6 Courses
- With Professional CertificationWith Professional Certification
- Beginner Friendly.75 hours75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With CertificateWith Certificate
- Beginner Friendly.24 hours24 hours
