Here are two ways to convert a character to an integer in Python:
- ord(): It is used to get the ASCII value of a character.
- int(): It is used when a character is a digit.
For example, the ord(“a”) function returns 97.
Method 1: Using the ord()
Example 1: Basic Usage
# For ASCII value
char = "K"
print(ord(char))
Output
75
Example 2: Check if is case-sensitive
The ASCII value of capital K is 75, but the small k’s value is different.
charData = "k"
print(ord(charData))
Output
107
Method 2: Using int()
# For digit value
digit_char = '2'
print(int(digit_char))
Output
2
That’s it!