How to Convert Python char to int

0
24711
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 users as they want.

Python char to int

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

Example

Let’s define a character and convert that character into an integer using the ord() function.

charData = "K"

print(ord(charData))

Output

75

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))

Output

107

You can see that it’s case-sensitive. This is because capital and small characters have different ASCII values.

Let’s take another character and convert it into an integer.

charData = "B"

print(ord(charData))

Output

107

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))

Output

K

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 a String to an integer since we are here dealing with characters, 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 Python char to int tutorial.

Related posts

Python string to list

Python string to json

Python string to datetime

Python string to list of characters

Python string to dictionary

Python string to hex

Python string to array

Python string to bytes

Python string to float

Leave A Reply

Please enter your comment!
Please enter your name here

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