chr() in Python

In this tutorial, we will learn to use the chr() method which is a built-in function in Python. This function returns a character from an integer that represents the specified Unicode code point which is supplied as a parameter to this function.

Syntax

The syntax of the function is shown below:-

chr(integer)

Parameters

An integer representing a valid Unicode code point.

Return Value

It returns a character whose Unicode code point is supplied as a parameter to this function.

Examples

Example 1: Get the character that represents the Unicode 70

The below program shows how the chr() is used.

a = chr(80)
print(a)

Output:

P

Example 2: Lets print CodeSpeedy

print( chr(67), chr(111), chr(100), chr(101), chr(83), chr(112), chr(101), chr(101), chr(100), chr(121))

Output:

C o d e S p e e d y

Example 3: Using a tuple/list of integers.

We can use Python data structures like lists or tuples to loop through a series of numbers.

string = ""
list = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
for i in range(0,len(list)):
   str = chr(list[i])
   string = string + str
   i=i+1
print(string)

Output:

Hello World

Example 4: Integer passed to chr() is out of the range.

print(chr(-5))

Output:

no output

We won’t get any output and the compiler will throw an error as shown below:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(chr(-5))  
ValueError: chr() arg not in range(0x110000)

The valid range of the integer is from 0 through 1,114,111. If the integer is outside the range, ValueError will be raised.

Thank you for reading this tutorial. I hope it helps you.

Also, you may visit:

Check whether a string contains unique characters in Python

Removing the first occurrence of a character in a string using Python

Count the number of Special Characters in a string in Python

Leave a Reply

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