The ord()
function returns the Unicode code point (integer) of a given character. It’s useful for working with characters, encoding, and text processing.
Example
print(ord("A"))
# Output: 65
The Unicode code point of 'A'
is 65
.
Syntax
ord(character)
- character → A single Unicode character.
- Returns → An integer representing the Unicode code point.
1. Getting Unicode Values of Characters
print(ord("a")) # Output: 97
print(ord("Z")) # Output: 90
print(ord("1")) # Output: 49
print(ord("@")) # Output: 64
Every character has a unique Unicode integer representation.
2. Finding Unicode for Emojis and Symbols
print(ord("😀")) # Output: 128512
print(ord("€")) # Output: 8364
print(ord("✓")) # Output: 10003
Works with special characters and emojis too.
3. Using ord()
in Sorting & Comparisons
print("b" > "a")
# Output: True (Because ord('b') = 98 and ord('a') = 97)
Compares characters based on Unicode values.
4. Converting Back with chr()
Use chr()
to convert Unicode back to a character.
print(chr(65)) # Output: A
print(chr(128512)) # Output: 😀
Useful for decoding Unicode values.
5. Validating Single Characters
char = "AB"
if len(char) == 1:
print(ord(char))
else:
print("Must be a single character!")
Ensures ord()
only processes one character at a time.
Key Notes
- ✔ Returns Unicode integer for a character.
- ✔ Works with letters, digits, symbols, and emojis.
- ✔ Useful for sorting and text encoding.
- ✔ Use
chr()
to convert back from Unicode to characters.
By using ord()
, you can process text, compare characters, and work with Unicode efficiently. 🚀
Leave a Reply