The ord() function in Python is a built-in function that is used to return an integer representing the Unicode code point of a given single character string. In other words, it returns the Unicode code point of a character in decimal format.
Syntax
ord(c)
Parameters
- c : A single character string whose Unicode code point is to be returned.
Return Value
The ord() function returns an integer representing the Unicode code point of the given character string.
Examples
Example 1: ord() function with ASCII characters
print(ord('A'))
Output
65
In this example, the ord() function is used to return the Unicode code point of the character ‘A’, which is 65 in decimal format.
Example 2: ord() function with non-ASCII characters
print(ord('ñ'))
Output
241
In this example, the ord() function is used to return the Unicode code point of the character ‘ñ’, which is 241 in decimal format.
Example 3: Using the ord() function with a string
print(ord("Hello"))
Output
TypeError: ord() expected a character, but string of length 5 found
In this example, an error is raised as the ord() function expects a single character string, but a string of length 5 is provided.
Use Cases
The ord() function can be useful in several cases, including:
- When converting characters to their corresponding ASCII values for storage or transmission purposes
- When working with Unicode characters and need to determine their code point representation
- When performing string comparisons or manipulations based on character values
In conclusion, the ord() function is a simple yet powerful tool for working with character strings in Python. It allows for easy conversion of character strings to their corresponding Unicode code point representation, making it a valuable addition to any Python programmer’s toolbox.