How to Convert a Character to an Integer and Vice Versa in Python

Hassan Saeed Feb 02, 2024
  1. Use chr() to Convert an Integer to a Character in Python
  2. Use ord() to Convert a Character to an Integer in Python
How to Convert a Character to an Integer and Vice Versa in Python

This tutorial discusses methods to convert a character to an integer and an integer to a character in Python.

Use chr() to Convert an Integer to a Character in Python

We can use the built-in function chr() to convert an integer to its character representation in Python. The below example illustrates this.

val = 97
chr_val = chr(val)
print(chr_val)

Output:

a

It will result in an error if you provide an invalid integer value to this. For example:

val = 1231232323
chr_val = chr(val)
print(chr_val)

Output:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-42-f76a9ed55c90> in <module>
      1 val = 1231232323
----> 2 chr(val)

ValueError: chr() arg not in range(0x110000)

Therefore, it is always good to put this code in a try...except block to catch the error, if any, and avoid any crash. The below example illustrates this:

val = 1231232323
try:
    chr_val = chr(val)
    print(chr_val)
except Exception as e:
    print("Error:", e)

Output:

Error: chr() arg not in range(0x110000)

Use ord() to Convert a Character to an Integer in Python

We can use the built-in function ord() to convert a character to an integer in Python. The below example illustrates this.

val = "a"
try:
    int_val = ord(val)
    print(int_val)
except Exception as e:
    print("Error:", e)

Output:

97

The above method also catches any invalid input and prints out the error instead of crashing the code. For example:

val = "aa"
try:
    int_val = ord(val)
    print(int_val)
except Exception as e:
    print("Error:", e)

Output:

Error: ord() expected a character, but string of length 2 found

Related Article - Python Character

Related Article - Python Integer