How to Convert Python char to int
In Python, all characters have an integer ASCII value. A char can either be represented as an ASCII value or, if the char comprises digits only, as the number it represents.
The conversion from char to int is an explicit type conversion in which the data type is manually modified by the user as they want.
Python char to int
To convert Python char to int, use the ord() method. The ord() function accepts a character and returns the ASCII value of that character.
The ord() is a built-in function that returns the number representing the Unicode code of a specified character.
Let’s define a character and convert that character into an integer using the ord() function.
charData = "K" print(ord(charData))
That means the ASCII value of the K character is 75.
The ASCII value of capital K is 75, but the ASCII value of small k is different.
charData = "k" print(ord(charData))
You can see that it’s case-sensitive. Captial and small characters have different ASCII values.
Let’s take another character and convert it into an integer.
charData = "B" print(ord(charData))
Converting Python int to char
To convert int to char in Python, use the chr() function. The chr() is a built-in function that takes an integer as an argument and returns a string representing a character at that code point.
In the above section, we converted chr to int, and in this section, we will convert into int to chr data type.
intData = 75 print(chr(intData))
In this example, we pass the ASCII value to the chr() function, converting it into a character. The character value of 75 is K because the chr() function takes an ASCII value as an argument and converts it into a character value.
This is different from converting String to an integer since we are here dealing with characters and not strings. To convert string to int, use the int() function, and converting int to string, use the str() function.
That is it for converting char to int in Python tutorial.