Python does not have a “char” data type, unlike other languages. But characters are just strings of length 1.
When converting a character to an integer, the character should be a Unicode/ASCII code point (e.g., ‘A’ → 65)or a digit (e.g., ‘5’ → 5). Each scenarios require a different approach.
Here are two ways:
- ord(): It is used to get the ASCII value of a character.
- int(): It is used when a character is a digit.
Method 1: Using the ord()
If your input is any character (e.g., ‘A’, ‘z’, ‘$’), convert it to its ASCII or Unicode code point using the ord() function.
# For ASCII value char = "K" print(ord(char)) # Output: 75
Checking if it is case-sensitive
The ASCII value of capital K is 75, but the small k’s value is different. So, it is case-sensitive.
charData = "k" print(ord(charData)) # Output: 107
TypeError: ord() expected a character
There is one catch with the ord() method: if the input is a multi-character string (e.g., ‘AB’), it will raise a TypeError: ord() expected a character.
char = 'AB' ascii_value = ord(char) print(ascii_value) # Output: TypeError: ord() expected a character, but string of length 2 found
To handle the potential error, you can use the try/except mechanism.
try: char = 'AB' if len(char) == 1: ascii_value = ord(char) print(ascii_value) else: raise ValueError("Expected a single character.") except TypeError: print("Invalid input: ord() expects a single character.") except ValueError as e: print(e) # Output: Expected a single character.
Empty character
If an input is an empty character, it will also raise a TypeError.
char = '' ascii_value = ord(char) print(ascii_value) # Output: TypeError: ord() expected a character, but string of length 0 found
Method 2: Using int()
When your input character represents a digit (like ’21’), and you want the numeric value 21, use the built-in int() method.
# For digit value digit_char = '2' print(int(digit_char)) # Output: 2
This approach is ideal for single-digit characters (‘0’ to ‘9’).
ValueError: invalid literal for int()
If the input variable is non-digit characters (e.g., ‘a’), it will throw a ValueError.
# For digit value digit_char = 'a' print(int(digit_char)) # Output: ValueError: invalid literal for int() with base 10: 'a'
Empty strings
If your input is an empty string, it will return a ValueError, too.
empty_char = '' print(int(empty_char)) # Output: ValueError: invalid literal for int() with base 10: ''
Best practice
You should use the .isdigit() method before converting to avoid potential error.
c = '5' if c.isdigit(): print(int(c)) else: print("Not a digit") # Output: 5
That’s it!