How to use the ord() method in Python

The ord method

In Python, the ord() method returns an integer value that represents a Unicode code for a specified character.

Syntax

The syntax of the ord() is given below:

ord(character)  

Parameter

  • character: This represents the Unicode character of length 1.

Return value

The ord() method returns an integer value that represents a Unicode code for a specified character.

Note: If the length of the character is more than 1, it throws an error.

Code

The following code shows how to use the ord() method in Python:

# create a variable
character = 'Z'
# store result
result = ord(character)
# display result
print(f"The integer value for the Unicode character {character}: {result}")

Explanation

  • Line 2: We create a variable named character and assign a Unicode character to it.

  • Line 4: We pass the value of character to the ord() function and then assign the result to a new variable, result.

  • Line 6: The result is displayed.

Free Resources