Skip to content

ord() function in Python

  • by

Using the ord() function you can get Unicode code from a given character in Python. This function returns the number representing the Unicode code of a specified character.

ord(ch)

ord() function in Python

A simple example code gets an integer representing the Unicode code point for the given Unicode character.

character = 'R'

unicode_char = ord(character)
print(unicode_char)

print(ord('5'))
print(ord('A'))
print(ord('$'))

Output:

ord() function in Python

It’s important to note that ord() only works for single characters. If you try to pass a string with multiple characters, it will raise a TypeError. For example:

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

To get the Unicode code points for each character in a string, you can use a list comprehension or a loop:

# Using list comprehension
unicode_points = [ord(char) for char in 'hello']
print(unicode_points)  # Output: [104, 101, 108, 108, 111]

# Using a loop
for char in 'hello':
    print(ord(char))

chr() functions

The chr() method returns a string representing a character whose Unicode code point is an integer.

value = ord("A")
 
# prints the unicode value
print (value)
 
# print the character
print(chr(value))

Output:

65
A

Do comment if you have any doubts or suggestions on this Python function.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *