Skip to content

Python ord() Function

How to use Python's built-in ord() function to convert a single Unicode character into its corresponding integer code point with syntax, examples, and error handling.

The ord() function returns an integer representing the Unicode character.

Syntax

ord(ch)

ord() Parameters

Python ord() function parameters:

Parameter Condition Description
ch Required A single character string.

ord() Return Value

Python ord() function returns an integer representing the Unicode character.

Examples

Example 1: Basic Usage

This example demonstrates the basic usage of the ord() function by converting lowercase and uppercase letters to their Unicode numeric representation.

print(ord('a'))  # Output:  97
print(ord('A'))  # Output:  65

output

97
65

Example 2: Unicode Characters

This example shows the ord() function being used with Unicode characters, converting them to their corresponding Unicode code points.

print(ord(u'a'))       # Output:  97
print(ord(u'\u2020'))  # Output:  8224

output

97
8224

Example 3: Exception Handling

This example demonstrates handling the TypeError that occurs when the ord() function is called with a string that contains more than one character.

print(ord('AB'))  # This will raise a TypeError

output

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(ord('AB'))  # This will raise a TypeError
TypeError: ord() expected a character, but string of length 2 found
Navigation