ord() function in Python
Python ord() function returns the Unicode code of a given single character. It is a modern encoding standard that aims to represent every character in every language.
Unicode includes:
- ASCII characters (first 128 code points)
- Emojis, currency symbols, accented characters, etc.
For example, unicode of 'A' = 65 and '€' = 8364. Let's look at a code example of ord() function:
print(ord('a'))
print(ord('€'))
print(ord('a'))
print(ord('€'))
Output
97 8364
Explanation:
- ord() function returns the unicode of the character passed to it as an argument.
- unicode of 'a' = 97 and '€' = 8364.
Syntax
ord(ch)
Parameter:
- ch: A single Unicode character (string of length 1).
Return type: it returns an integer representing the Unicode code point of the character.
Examples of ord() Function
Example 1: Basic Usage of ord()
In this example, We are showing the ord() value of an integer, character, and unique character with ord() function in Python.
print(ord('2'))
print(ord('g'))
print(ord('&'))
print(ord('2'))
print(ord('g'))
print(ord('&'))
Output
50 103 38
Note: If the string length is more than one, a TypeError will be raised. The syntax can be ord("a") or ord('a'), both will give the same results. The example is given below.
Example 2: Exploring ord() with Digits and Symbols
This code shows that ord() value of "A" and 'A' gives the same result.
v1 = ord("A")
v2 = ord('A')
print (v1, v2)
v1 = ord("A")
v2 = ord('A')
print (v1, v2)
Output
65 65
Example 3: String Length > 1 Causes Error
The ord() function only accepts a single character. If the string length is more than 1, a TypeError will be raised.
print(ord('AB'))
print(ord('AB'))
Output:
Traceback (most recent call last):
File "/home/f988dfe667cdc9a8e5658464c87ccd18.py", line 6, in
value1 = ord('AB')
TypeError: ord() expected a character, but string of length 2 found
Example 4: Using Both ord() and chr()
chr() function does the exact opposite of ord() function, i.e. it converts a unicode integer into a character. Let's look at an example:
v= ord("A")
print (v)
print(chr(v))
v= ord("A")
print (v)
print(chr(v))
Output
65 A
Related articles: