This post will discuss how to convert a character to an integer in Python and vice versa.

1. Convert a character to an integer in Python

In the following section, we will see different methods to convert a character to an integer:

1. Using ord() function

The standard solution to convert a character to an integer is using the built-in function ord(). This function takes a single-character string as an argument and returns its code point as an integer. For example, ord('A') returns the integer 65.

Download  Run Code

 
This method is concise and works for any single-character string. However, it may raise an exception if the argument is not a single-character string. For example, if we try to pass an empty string or a multi-character string, we will get ‘TypeError: ord() expected a character, but string of length 0 found’.

2. Using binascii module

Another way to convert a character to an integer in Python is to use the binascii.hexlify() function from the binascii module. It takes a bytes-like object as an argument and returns its hexadecimal representation as a bytes object. The idea is to first convert the character to a bytes object using the encode() function and pass it to the binascii.hexlify() function to get its hexadecimal representation as a bytes object. Then convert the hexadecimal to an integer using built-in function called int(). For example:

Download  Run Code

2. Convert an integer to a character in Python

Now that we know how to convert a character to an integer in Python, let’s see how we can do the reverse operation: converting an integer to a character:

1. Using chr() function

The simplest way to convert an integer to a character in Python is to use the built-in chr() function. The ord() function is the inverse of built-in function chr(). It takes an integer as an argument and returns its corresponding character as a string. For example, chr(65) returns the string 'A', as shown below:

Download  Run Code

 
This method is very simple to use, but may raise an exception if the integer is not a valid code point. For example, if we try to pass a negative integer or a large integer, we will get ‘ValueError: chr() arg not in range(0x110000)’.

2. Using binascii module

Another option to convert an integer to a character in Python is using the binascii.unhexlify() function from binascii module. It takes a hexadecimal string as an argument and returns a bytes object containing its binary data. The idea is to first convert the integer to a hexadecimal string using the hex() function, and then pass the hexadecimal string to the binascii.unhexlify() function to obtain a bytes object containing the binary data. Then convert the bytes object to a character using the built-in function decode(). For example:

Download  Run Code

That’s all about conversion between character and integer in Python.