×

chr() and ord() Functions in Python

Python language contains many built-in functions which we use for many programs to work efficiently. The chr() and ord() are a few built-in functions in Python that are used for conversions. These both functions have their separate conversion functions. In this article, let us discuss the chr() function and the ord() function. We will complete these functions by understanding some example codes and references.

Understanding the Odr() function:

The ord() is a built-in function in python language that is used to convert a specific character into an integer. The ord() function will take a string argument from a single code character and outputs its integer value. Ord() function is opposite to the char() function

The syntax we use for this function is as follows:

ord(a)

now let us look at an example code

Let us take a string of length one, which will return an integer presenting the Unicode. When an argument is a Unicode object, it will be the value of an 8-bit string. So we have to make sure the input we take for conversion must be of length "1." For this example, we take the code as

code 1:

print(ord('A'))
print(ord('a'))
print(ord('@'))
print(ord('b'))
print(ord('#'))
print(ord('L'))

Output:

65
97
64
98
35
76

Code 2:

print(ord('hello'))

Output:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: ord() expected a character, but string of length 5 found
>

So as we can see in code 1, we used the Unicode object and the ASCII table to get the values.

chr() and ord() Functions in Python

For code 2, we gave input of 5 characters, and once we ran the code, we got an error message because the ord() method only accepts single characters, not multiple characters.

For a clear picture, let us look below at the ASCII table for reference values for every input character we take.

With this, we got an idea of what the ord() function and their works.

Understanding the chr() function:

This chr() is a python's built-in function that is used for converting an integer into a special character. There is a specific range to find the value of the integer, and the range lies between 0 to 1,114,111. We have to ensure that the integer input we give must be between this range, or we will get an error in the output. This function works all opposite to the ord() function.

The syntax we use for this function is given below

String chr(n)

n is where we give the integer input of range 0 to 1,114,111.

To understand this concept better, let us look at an example code.

Code:

print(chr(3))
print(chr(5))
print(chr(88))
print(chr(100))
print(chr(40))
print(chr(150))

Output:

 


X
d
(
?
>

Looking at the above code, we took some integers as the values for n and got the respected conversions as the output.

Code 2:

print(chr(-5))

Output:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ValueError: chr() arg not in range(0x110000)

In this code 2, we gave an integer that is not taken from the range of n, so we got an error as an output. It is very important to provide an integer between the range as an input.

Let us look at the Unicode character table used for giving outputs based on the input integers.

chr() and ord() Functions in Python

Using this table, we will understand on What bases we will get our outputs.

Hexa decimal data:

In the ord() and chr() functions, we can also pass integers in the hexadecimal format, like (base 15). We will get proper outputs only if we add a prefix to the integer. To understand this concept better, let us look at an example code

Code:

print(hex(18))
print(chr(0x16))
print(ord('\x12'))

Output:

0x12


18

This code passed the hexadecimal value in the chr() and ord() functions. And got the respective outputs.

With this, we got an idea of the chr() function and its working.

Conclusion:

So far, in this article, we have covered a few built-in functions of python, which are chr () and ord(). These functions are mainly used for conversions. We learned about the essential functions of these conversions and the working of these functions, such as the syntax of the functions and the example codes used for the chr to int and int to char conversions. Finally, we have seen about the hexadecimal data where we learned that in python, we could also use the hexadecimal data just by adding a prefix to the integer and adding the required range to it. In this concept, we also discussed an example code inserting the hexadecimal values to this chr () and ord() functions.


Related Topics

How to Import Files in Python

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to implement classifiers in Python

What is classification? Classification is a type of supervised machine learning problem with a categorical target (response) variable. Given the known label in the training data, the classifier approximates a mapping...

4 minutes read.

Problem-solving with algorithm and data structures using Python

What is problem-solving? There is no universal method for solving problems. It's frequently a special process that balances your immediate and long-term goals with your available resources. However, several models emphasise...

3 minutes read.

Length of Tuple in Python

What is Tuple? Python is a data structure in a python programming language; it is the collection of the objects in a sequence. The tuples are immutable; that is, we cannot...

3 minutes read.

Checking whether a String Contains a Set of Characters in python

In this tutorial, we will learn how to examine or check whether a string contains any set of characters or a substring and if it contains, we will learn how...

6 minutes read.

Python List copy() method

Python List copy () method The list.copy () method returns a shallow copy of the list. Syntax list.copy() Parameter NA Return This function returns the copy for the given list. Example 1 # Python program explaining # the list.copy() method # passing the...

1 minute read.

Keyboard Jump Game in Python

Keyword hop (jump) game is a speed composing game that aides in further developing the composing velocity of players The object of Keyboard Jump (hop) Game Python Project is to fabricate...

7 minutes read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 minutes read.

Python if statement

Python if statement Decision making is an essential feature of any programming languages. Condition checking is the strength of decision making. Python provides many decision-making statements, such as: If statementIf-else statementelif statement if statement The if statement is...

2 minutes read.

Assignment Operators in Python

The prime usage of Assignment Operators is to assign values to variables. These are taken into account to do operations on values and variables. There are some special symbols in python...

4 minutes read.

Wikipedia module in Python

Wikipedia module in Python: The internet has become an essential part of all of our life which is the largest source of all the information. Therefore, it becomes very important...

7 minutes read.

Flutter with tensor flow in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

3 minutes read.

Python Read CSV file

The CSV stands for “comma-separated value,” which is defined as a simple file format that is used to store data into a tabular form such as a database or spreadsheet. It is...

7 minutes read.

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three...

3 minutes read.

ModuleNotFoundError No module named 'mysql' in Python

mysql module not found is an error that occurs in python. It appears like ModuleNotError: No module named 'mysql.' This error occurs when you forget to install a module called...

3 minutes read.

List Index out of Range Python for Loop

The List is generally used in Python to store multiple items or elements inside one single variable. The List is ordered in nature, the List can contain the elements inside...

3 minutes read.

Python program to find Fibonacci series

Python program to find Fibonacci series A Fibonacci series is an integer sequence of 0, 1, 1, 2, 3, 5, 8.... We can identify the Fibonacci series as any number sequence...

2 minutes read.

Python Program to Print Sum of all Elements in an Array

Python program to print sum of all elements in an array A set of objects stored in contiguous memory locations is referred to as an array. The concept is to keep...

2 minutes read.

An Introduction to Mocking in Python

Python Mocking is a testing library. It enables you to substitute portions of your system under test with fake(mock) objects and make assertions about how they were utilized.  The test is...

3 minutes read.

Python Not Equal Operator

Python provides us with many operators to make tasks easier. There are about 7 categories of operators in Python. One of the 7 classifications is the comparison operators. Just as...

3 minutes read.