How to convert an integer to a character in Python?



To convert an integer to a character in Python, we can use the chr() method. The chr() is a Python built?in method that returns a character from an integer. The method takes an integer value and returns a unicode character corresponding to that integer.

Syntax

char(number)

Parameter

The method takes a single integer between the range of 0 to 1,114,111.

Return Value

A unicode character of the corresponding integer argument. And it will raies a ValueError if we pass an out of range value (i,e. range(0x110000)). Also it will raise TypeError ? for a non?integer argument.

Example

In this example, we have used the chr() method to convert an integer 100 to the corresponding unicode characters. Here, the method returns a character d for the given integer.

Open Compiler
number = 100 # apply chr() function on integer value result = chr(number) print("Integer - {} converted to character -".format(number), result)

Output

Integer - 100 converted to character - d

Example

From this example we can see that the unicode character of 35 is #, and for 2000 is ?.

Open Compiler
number1 = 35 number2 = 2000 # apply chr() function on integer values print("Integer - {} converted to character -".format(number1), chr(number1)) print("Integer - {} converted to character -".format(number2), chr(number2))

Output

Integer - 35 converted to character - #
Integer - 2000 converted to character - ?

Example

In this example we have passed a negative integer that is out of range, so that the method returns a ValueError.

Open Compiler
number = -100 # apply chr() function on out of range value print(chr(number))

Output

Traceback (most recent call last):
  File "/home/cg/root/62945/main.py", line 4, in <module>
    print(chr(number))
ValueError: chr() arg not in range(0x110000)

Example

In here, we have passed An integer that is outside the range, so that the method returns a ValueError.

Open Compiler
number = 1114113 # apply chr() function on out range value print(chr(number))

Output

Traceback (most recent call last):
  File "/home/cg/root/69710/main.py", line 4, in <module>
    print(chr(number))
ValueError: chr() arg not in range(0x110000)

Example

In this example, we have passed a Non?Integer argument to the chr() method. Due to this the method returns a TypeError.

Open Compiler
Parameter_ = 'abc' # apply chr() function on non integer value print(chr(Parameter_))

Output

Traceback (most recent call last):
  File "/home/cg/root/40075/main.py", line 4, in 
    print(chr(Parameter_))
TypeError: 'str' object cannot be interpreted as an integer
Updated on: 2023-08-23T18:36:02+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements