Skip to content
Related Articles
Open in App
Not now

Related Articles

chr() in Python

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 26 Jul, 2022
Improve Article
Save Article

The Python chr() function returns a string from a Unicode code integer.

Python chr() Function Syntax:

Syntax: chr(num)

  • num: an Unicode code integer

Return: Returns str

Python chr() Function Example

Here, we are going to use Python chr() methods to get the string of Unicode.

Python3




print(chr(97))

Output:

a

Example 1:

Suppose we want to print ‘G e e k s f o r G e e k s’. 

Python3




# Python program to illustrate
# chr() builtin function
 
print(chr(71), chr(101),
chr(101), chr(107),
chr(115), chr(32),
chr(102), chr(111),
chr(114),chr(32),
chr(71), chr(101),
chr(101), chr(107),
chr(115))

Output:

G e e k s   f o r   G e e k s

Example 2: 

Printing character for each Unicode integer in numbers list.

Python3




# Python program to illustrate
# chr() builtin function
 
numbers = [17, 38, 79]
 
for number in numbers:
     
    # Convert ASCII-based number to character.
    letter = chr(number)
    print("Character of ASCII value", number, "is ", letter)

Output:

Character of ASCII value 17 is  
Character of ASCII value 38 is  &
Character of ASCII value 79 is  O

What happens if we give something out of range?

Python3




# Python program to illustrate
# chr() builtin function
# if value given is
# out of range
 
# Convert ASCII-based number to character
print(chr(400))

Output:

No Output

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

Traceback (most recent call last):
  File "/home/484c76fb455a624cc137946a244a9aa5.py", line 1, in 
    print(chr(400))
UnicodeEncodeError: 'ascii' codec can't encode character 
'\u0190' in position 0: ordinal not in range(128)

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!