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!
Related posts
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.