Python ord(): A Step-By-Step Guide

In Python ord() function accepts a single unit of character and returns the equivalent Unicode code value of the passed argument. In other words, the ord() function can take a string or character of length one and returns an integer representing the Unicode of that string or character.

ord() Function in Python 

The ord() function is nothing but the inverse of the Python chr() function. In the chr() function, we will convert the Unicode integer to the character, and in the ord(), it will be the exact opposite in the ord ().

Syntax – ord(ch)

Parameters: Accepts Unicode character or string of length 1.

Return Value: Returns an integer representing the Unicode character

Example ord() vs chr() 

print(chr(97))
print(ord('a'))

Output

a
97

As you can see, the chr(97) returns character ‘a’, and the inverse ord('a') returns the integer 97

ord() Function Examples

Let’s take a look at different types of example.

print('Unicode value of lower case alphabet a is ', ord('a')) # lower case alphabet 
print('Unicode value of bumber 5 is ', ord('5')) # Number
print('Unicode value of symobol $ is ', ord('$')) # dollar
print('Unicode value of upper case alphabet A is ', ord('A')) # Upper case alphabet
print('Unicode value of zero is ', ord('0')) # Number Zero

Output

Unicode value of lower case alphabet a is  97
Unicode value of bumber 5 is  53
Unicode value of symobol $ is  36
Unicode value of upper case alphabet A is  65
Unicode value of zero is  48

TypeError: ord() expected a character, but string of length 2 found.

If the argument passed to the ord() function is more than 1 character, then Python will raise a TypeError: ord() expected a character, but string of length 2 found.

print(ord('AB'))

Output

Traceback (most recent call last):
  File "c:\Projects\Tryouts\main.py", line 9, in <module>
    print(ord('AB'))
TypeError: ord() expected a character, but string of length 2 found
Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
Importerror No Module Named Pandas

ImportError: No module named Pandas

In Python, if you try to import pandas without installing the module using pip, you will get ImportError: no module named pandas error.  In this tutorial, let’s look at installing…
View Post
Indentationerror Unexpected Indent

IndentationError: unexpected indent

Table of Contents Hide What are the reasons for IndentationError: unexpected indent?Python and PEP 8 Guidelines Solving IndentationError: expected an indented blockExample 1 – Indenting inside a functionExample 2 – Indentation…
View Post
Python String Capitalize()

Python String capitalize()

Table of Contents Hide capitalize() Syntaxcapitalize() ParameterReturn Value from capitalize()Example: Capitalize a string in Python Python string capitalize() method will convert the first letter in a string to uppercase and keep…
View Post