Before we start, generally and in this article, int refers to integer. Converting a string to an integer using Python is something that is very common when it comes to programming involving numbers. Whether you are handling user input, processing API responses, or simply reading from a file, knowing how to convert strings to integers is fundamental. In this article, let us take you through the various methods to do this, their advantages and disadvantages, and some best practices.
How to Convert String to Int using int() Function
Let us start with the easiest and the most straightforward way to convert a string to integer using Python: the int() function. Why do we recommend this first? Because this function comes built in. Use this syntax as a guide:
num_str = "123" num_int = int(num_str) print(num_int) # Output: 123
Why should you use int() function when there are alternatives available?
If you had notices, at PythonCentral we start most of the Python tutorials with the int() function because it is simple and efficient. It works for both positive and negative integers. But there is a problem. It could flag the "ValueError" message when the string is not a valid integer. You can easily fix this error. This happens when you try to convert an invalid string. Handle this error by using the "try-except" block. Here is how you can do this:
num_str = "123PythonCentral" try: num_int = int(num_str) print(num_int) except ValueError: print("Invalid input: Cannot convert to int")
In this string, we appended PythonCentral next to the integer 123. Always use validate input before conversion. Use try-except to handle edge cases gracefully.
How to Convert Strings with Whitespaces
The int() function automatically trims the leading and trailing whitespaces before conversion. For example, let us use a syntax with space before and after the integer:
num_str = " 23 " num_int = int(num_str) print(num_int)
The output will contain just 23. The blank space does not affect the conversion. The invalid characters like we saw earlier are the only problems that will raise an error.
How to Convery Strings with Different Bases
Python lets you convert strings with different numeral bases like binary, octal, or hexadecimal using the init() function.
binary_str = "1010" binary_int = int(binary_str, 2) print(binary_int)
This script will give you 10 as the output because the operator binary_str, 2 indicates that this is binary. Let us look at a different syntax now:
hex_str = "1F" hex_int = int(hex_str, 16) print(hex_int)
By now you would have guessed what happened here. The output would be 31, because with the operator hex_str, 16 we indicated that this is hexadecimal. Base conversion helps when you are working with binary and hexadecimal numbers. The init function allows conversion from base 2 to base 36.
How to Use ast.literal_eval to Convert String to Integer
There may be some cases where you will need a safer evaluation. In those cases, use the ast.literal_eval() function from the "ast" module. Here is an example to understand this function better:
import ast num_str = "100" num_int = ast.literal_eval(num_str) print(num_int)
The output will display 100. You can use this function for parsing numeric values. An added advantage is that this function avoids arbitrary code execution.
Which is Better? init() or literal_eval?
Why don't we run a simple experiment and find it for ourselves with evidence. Let us write a script to see which function gets the results faster. For this, we will use the timeit function.
import timeit num_str = "12345" print("int():", timeit.timeit(lambda: int(num_str), number=1000000)) print("literal_eval():", timeit.timeit(lambda: ast.literal_eval(num_str), number=1000000))
The output of this script clearly shows that the init() function is faster. You can prefer this function for simple conversions. The literal_eval function is slower but much safer. Use this when you are working on complex tasks.
Wrapping Up
Converting a string to an integer in Python is very simple with the int() function in your arsenal. But be a little cautious when you are handling invalid inputs, whitespaces, and different bases. They require certain additional considerations which you have learnt now. By understanding these techniques, your Python code to convert a string to an int is now ready.