How to convert a char to int in Python
Learn how to convert char to int in Python. You'll find different methods, tips, real-world applications, and how to debug common errors.
.png)
Python developers often need to convert characters to integers for data processing and numerical operations. The language offers built-in functions like int() and ord() that make this simple and efficient.
In this article, you'll learn various conversion techniques and their real-world applications. You'll also get practical tips and debugging advice to handle common errors and master these transformations.
Using the ord() function
char = 'A'
ascii_value = ord(char)
print(ascii_value)--OUTPUT--65
The ord() function is Python's direct tool for converting a single character into its integer representation. It returns the Unicode code point for the character—in this case, ord('A') returns 65, which is its standard ASCII value.
This is particularly useful when you need to perform mathematical operations on characters, implement custom sorting logic, or work with character-based encryption where numerical manipulation is key.
Basic techniques for numeric characters
Beyond the general-purpose ord() function, you can use specialized tools like int(), character arithmetic, or eval() to handle conversions for numeric characters.
Converting numeric characters with int()
numeric_char = '5'
integer_value = int(numeric_char)
print(integer_value)--OUTPUT--5
The int() function is the most straightforward way to convert a string containing a number into an actual integer. Unlike ord(), which gives you a character’s Unicode value, int() parses the string and returns its numerical equivalent. So, int('5') correctly produces the number 5, not its ASCII code.
- This method is ideal for processing user input or numerical data read from files.
- Keep in mind that it only works for strings representing whole numbers. If you try
int()on a non-numeric string like'A', Python will raise aValueError.
Character arithmetic with ASCII offsets
digit_char = '7'
integer_value = ord(digit_char) - ord('0')
print(integer_value)--OUTPUT--7
This technique cleverly uses the fact that numeric characters '0' through '9' have consecutive code points in standard character sets. By subtracting the code point of '0' from the code point of any digit character, you can find the integer value. The expression ord('7') - ord('0') calculates the numerical distance between these characters, which results in the integer 7.
- It's a fast, low-level way to handle conversions, especially useful in performance-critical algorithms where you want to avoid the overhead of function calls like
int().
Using eval() for numeric character evaluation
numeric_char = '9'
integer_value = eval(numeric_char)
print(integer_value)--OUTPUT--9
The eval() function is a powerful tool that parses and executes a string as a Python expression. When you pass it a string like '9', it evaluates the content and returns the integer 9. It essentially asks Python to run the code held within the string.
- While it works for simple numbers,
eval()can execute any valid Python code. This creates a significant security risk if you use it with untrusted input. - Due to its complexity, it's generally slower than safer alternatives like
int(). It's best to avoideval()for simple type conversions.
Advanced character to integer conversions
Beyond single-character conversions, you can use more advanced tools to process entire sequences at once or handle specialized formats like hexadecimal characters.
Converting multiple characters with list comprehension
chars = '123'
integer_values = [int(c) for c in chars]
print(integer_values)--OUTPUT--[1, 2, 3]
List comprehension offers a concise and readable way to create lists from other iterables. The expression [int(c) for c in chars] builds a new list by applying an operation to each character in the string '123'.
- It iterates through each character (
c) in thecharsstring. - For each character, it calls
int()to convert it into its integer equivalent. - Finally, it collects these new integers into a single list, resulting in
[1, 2, 3].
This one-liner is often more efficient and is considered more "Pythonic" than writing a traditional for loop to do the same job.
Using map() function for batch conversion
chars = '456'
integer_values = list(map(int, chars))
print(integer_values)--OUTPUT--[4, 5, 6]
The map() function offers another clean way to handle batch conversions. It works by applying a function, like int(), to every character in an iterable such as the string '456'.
- It returns a special
mapobject, which is an iterator that processes items one by one. - You'll need to convert this object into a list using
list()to see all the resulting integers at once.
This method is functionally similar to list comprehension but is sometimes preferred for its directness when you're just applying a single function.
Converting hexadecimal characters to integers
hex_char = 'F'
integer_value = int(hex_char, 16)
print(integer_value)--OUTPUT--15
The int() function can do more than just handle standard numbers; it accepts an optional second argument to specify the number's base. By passing 16, you tell Python to interpret the string as a hexadecimal value.
- The expression
int('F', 16)correctly converts the hex character'F'into its decimal equivalent, which is15. - This technique works for any valid hex digit (
'0'-'9'and'A'-'F') and is essential when you're parsing data formats that rely on hexadecimal notation, like web colors or memory addresses.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
The conversion techniques we've covered, from using ord() for ASCII values to int() for numeric strings, are the building blocks for powerful tools. Replit Agent can turn these concepts into production-ready applications.
- Build a hexadecimal color converter that transforms web color codes into their RGB integer equivalents.
- Create a data validation tool that parses character-based input and converts it into numerical data for processing.
- Deploy a simple text encryption utility that uses character arithmetic with
ord()to shift letters and encode messages.
Bring your own app idea to Replit Agent. It will write the code, run tests, and fix bugs for you, turning your concept into a deployed application.
Common errors and challenges
While Python makes character conversions straightforward, a few common pitfalls can trip you up if you're not careful.
Handling the TypeError when using ord() with multiple characters
The ord() function is designed to work on a single character only. If you pass it a string containing more than one character, Python will raise a TypeError.
- This happens because the function expects an input of length one, so an argument like
'10'or'AB'will fail. - To avoid this, make sure you're processing strings one character at a time, either by iterating through them or by accessing a specific index.
Confusion between ord() and int() for numeric characters
It's easy to mix up ord() and int(), but they serve very different purposes for numeric characters.
- Remember that
ord('5')returns the character's Unicode code point (which is53), not the number five. - In contrast,
int('5')correctly parses the string and returns the integer5. - Using the wrong function will lead to unexpected results in your calculations, so always choose
int()when you need the actual numeric value of a digit string.
Case conversion errors using ASCII arithmetic
When performing character arithmetic, it's crucial to account for letter casing. Uppercase and lowercase letters have different ASCII values, which can break your logic.
- For example,
ord('a')andord('A')return different integer values (97and65, respectively). - If your code expects an uppercase letter but receives a lowercase one, any calculations based on its ASCII value will be incorrect.
- A simple fix is to standardize your input first by converting all characters to a consistent case using methods like
.upper()or.lower().
Handling the TypeError when using ord() with multiple characters
A common pitfall is giving the ord() function more than it can handle. It's built to process exactly one character, so passing a longer string will immediately trigger a TypeError. Take a look at the following code to see it happen.
text = "ABC"
ascii_value = ord(text) # This will raise TypeError
print(ascii_value)
The TypeError occurs because the ord() function is given the entire string "ABC" at once, but it's designed to process only one character at a time. See how to correctly iterate through the string in the example below.
text = "ABC"
ascii_values = [ord(char) for char in text]
print(ascii_values)
To fix this, you must process the string one character at a time. The solution uses a list comprehension, [ord(char) for char in text], which iterates through the string and applies the ord() function to each character individually.
- This correctly returns a list of their ASCII values instead of causing an error.
- You'll often encounter this issue when processing strings from user input or files, where the length isn't guaranteed to be one.
Confusion between ord() and int() for numeric characters
It's a classic mix-up: you need the number from a character string, but you reach for ord() instead of int(). This mistake doesn't convert the digit to its value—it fetches its code point. The following example shows this common error in action.
digit = "5"
value = ord(digit)
print(value) # Prints 53, not 5
Using ord() on a numeric character like '5' fetches its ASCII code point, 53, instead of the integer 5 you likely want. This common mix-up can silently break your logic. See the correct approach in the example below.
digit = "5"
value1 = int(digit)
value2 = ord(digit) - ord('0')
print(value1, value2) # Both print 5
To get the actual number from a numeric character, use one of these correct methods. This is crucial when you need to perform mathematical operations on digits read as strings.
- Use the
int()function, which directly parses the string and returns its integer value. - Use character arithmetic by subtracting the code point of
'0'from your digit's code point.
Both int('5') and ord('5') - ord('0') correctly yield the integer 5.
Case conversion errors using ASCII arithmetic
When using ASCII arithmetic for tasks like case conversion, you must account for the different code points of uppercase and lowercase letters. Applying a fixed offset universally can lead to incorrect results, especially when your string contains mixed characters. The code below demonstrates this.
text = "Hello, World! 123"
result = ""
for char in text:
result += chr(ord(char) - 32) # Will cause issues with non-letters
print(result)
This code incorrectly subtracts 32 from every character's code point, corrupting anything that isn't a lowercase letter. This universal offset garbles spaces, punctuation, and numbers. See the correct way to handle this below.
text = "Hello, World! 123"
result = ""
for char in text:
if 'a' <= char <= 'z':
result += chr(ord(char) - 32)
else:
result += char
print(result)
The solution is to apply the conversion selectively. By checking if a character falls within the lowercase range with if 'a' <= char <= 'z', you ensure the ASCII offset only affects lowercase letters. The else clause leaves all other characters—like numbers or punctuation—untouched, which prevents data corruption.
- You'll want to use this conditional logic whenever you're processing mixed-character strings and need to modify only specific letter cases.
Real-world applications
After navigating the common pitfalls, you can see how these techniques power practical applications like password validation and text analysis.
Checking password strength with ord() character codes
You can use ord() to enforce password complexity rules by checking if each character's code point falls within the required ranges for uppercase letters, digits, or symbols.
password = "P@ssw0rd"
has_uppercase = any(ord('A') <= ord(c) <= ord('Z') for c in password)
has_digit = any(ord('0') <= ord(c) <= ord('9') for c in password)
print(f"Has uppercase: {has_uppercase}, Has digit: {has_digit}")
This code snippet efficiently checks for password complexity using generator expressions inside the any() function. This approach is highly performant because any() stops searching as soon as it finds a character that meets the condition.
- The first check,
any(ord('A') <= ord(c) <= ord('Z') for c in password), iterates through the password. It usesord()to see if any character's code point falls within the uppercase 'A' to 'Z' range. - Similarly, the second check confirms the presence of at least one digit.
Processing text data with ASCII value manipulation
By combining the ord() and chr() functions, you can perform custom text transformations, like converting a string to uppercase, character by character.
text = "Hello, World!"
result = ""
for char in text:
if ord('a') <= ord(char) <= ord('z'):
result += chr(ord(char) - 32) # Difference between lowercase and uppercase
else:
result += char
print(f"Original: {text}")
print(f"Uppercase: {result}")
This snippet demonstrates a fundamental text processing technique. It builds a new string, result, by looping through the original text.
- Inside the loop,
ord()gets the integer code for each character. - A key part of the logic is subtracting 32 from the code of any lowercase letter. This is a classic trick that leverages the consistent 32-point gap between lowercase and uppercase letters in the ASCII standard.
- Finally,
chr()turns the resulting integer back into a character, which is then appended to the new string.
Get started with Replit
Put your knowledge into practice by building a real tool. Tell Replit Agent to “build a password strength checker using ord()” or “create a simple hex-to-decimal converter web app.”
The agent writes the code, tests for errors, and deploys your app from a single prompt. Start building with Replit and bring your idea to life.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.


.png)
.png)