AppDividend
Latest Code Tutorials

How to Convert Python Int to Char

0

In Python, a char can either be defined as an ASCII value or, if the char carries digits only, as the number it represents. In ASCII, a particular numerical value is given to different characters and symbols for computers to store and manipulate.

To find an ASCII value of a character, use the ord() function. Let’s see how to convert ASCII value to character value.

Python int to char

To convert int to char in Python, use the chr() method. The chr() is a built-in Python method that returns a character (a string) from an integer (it represents the Unicode code point of the character).

Syntax

chr(i)

Arguments

The chr() method takes a single parameter which is an integer.

Return Value

The chr() function returns a character (a string) whose Unicode code point is the integer.

Example

Let’s use the chr() function to convert int to a character.

print(chr(97))

print(chr(65))

print(chr(1100))

Output

a
A
ь

And we get the characters the output concerning its ASCII value. The chr() method returns a character whose Unicode point is num, an integer.

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

If we pass the negative value to the chr() function then it returns ValueError: chr() arg not in range(0x110000).

print(chr(-11))

Output

Traceback (most recent call last):
  File "/Users/krunal/Desktop/code/pyt/database/app.py", line 7, in <module>
    print(chr(-1))
ValueError: chr() arg not in range(0x110000)

An integer we have passed is outside the range, and then the method returns a ValueError.

Convert a list of integers to characters

To create a list in Python, use the [ ] and add the values inside it.

listA = [69, 72, 78, 81, 90, 99]

for number in listA:
    char = chr(number)
    print("Character of ASCII value", number, "is ", char)

Output

Character of ASCII value 69 is  E
Character of ASCII value 72 is  H
Character of ASCII value 78 is  N
Character of ASCII value 81 is  Q
Character of ASCII value 90 is  Z
Character of ASCII value 99 is  c

Convert Python char to int

To convert char to int in Python, use the ord() method. The ord() is a built-in Python function that returns a number representing the Unicode code of a specified character.

print(ord('K'))
print(ord('B'))
print(ord('#'))
print(ord('~'))

Output

75
66
35
126

Conclusion

To convert int to character, use the chr() function. To convert integer to character, use the ord() function.

That is it for this tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.