Python ord() Function
The ord() function in Python returns the Unicode code point (an integer) for a given character. It is the reverse of the chr() function.
Syntax
ord(character)
Parameters:
character– A string representing a single Unicode character.
Returns:
- An integer representing the Unicode code point of the given character.
Example 1: Using ord() with a lowercase letter
print(ord('a'))
97
Example 2: Using ord() with an uppercase letter
print(ord('A'))
65
Example 3: Using ord() with a special character
print(ord('@'))
64
Use Cases
- Comparing characters based on Unicode values
- Implementing custom sorting algorithms
- Converting characters to numbers in cryptographic or hashing applications
ord() with Unicode Characters
print(ord('₹')) # Rupee symbol
8377
This works with any character in the Unicode standard, not just English letters.
Common Mistakes
- Passing more than one character:
ord('ab')will raise aTypeError. - Passing an empty string:
ord('')will also raise aTypeError.
Interview Tip
The ord() function is often used in problems that involve character frequency, shifting characters (like in Caesar cipher), or sorting letters.
Summary
ord()converts a character to its Unicode code point.- It accepts exactly one character.
- Works with any character in the Unicode set.
Practice Problem
Write a program that takes a character as input and prints its Unicode value.
ch = input("Enter a character: ")
if len(ch) == 1:
print("Unicode code point is:", ord(ch))
else:
print("Please enter exactly one character.")
Comments
Loading comments...