Strings and Integers are two important data types in Python. Many times, you have to convert a Python string to an integer. Hence, we added different ways to achieve this conversion.
How to Convert Strings to Integers in Python
By the end of this tutorial, you shall be able to use them in your Python programs.
Python Methods to Convert Str to Int
Before we go, refer to this simple tutorial to convert Python string to integer and back string. It too lists multiple ways to convert a string to an integer.
Using Int()
Function
The most straightforward way to convert a string to an integer in Python is by using the int()
function. This function takes a string as an argument and returns its integer representation.
# Example: Using int() function
str_num = "123"
int_num = int(str_num)
print(f"Original String: {str_num}, Converted Integer: {int_num}")
Output:
Original String: 123, Converted Integer: 123
Handling Errors with Int()
When using int()
, keep in mind that it may raise a ValueError
if the string cannot be converted to an integer. To handle this, you can use a try-except block.
# Example: Handling ValueError
str_num = "abc"
try:
int_num = int(str_num)
print(f"Converted Integer: {int_num}")
except ValueError:
print(f"Conversion failed. The input is not a valid integer.")
Output:
Conversion failed. The input is not a valid integer.
Using Float()
and Round()
These two Python functions float() and round() when used together can converge strings to integers.
For example, when you have a decimal number in string form, first, use float() to convert it to a float. Finally, apply the round() function to produce an integer value.
# Example: Using float() and round()
str_num = "456.78"
float_num = float(str_num)
int_num = round(float_num)
print(f"Original String: {str_num}, Converted Integer: {int_num}")
Output:
Original String: 456.78, Converted Integer: 457
This method is useful when dealing with numeric strings that may have decimal points.
Using Eval()
to Convert String to Integer
The eval()
function evaluates a Python expression from a string and returns the result. While powerful, it should be used with caution as it can execute arbitrary code. When used for converting strings to integers, it’s essential to ensure the input is safe.
# Example: Using eval()
str_num = "789"
int_num = eval(str_num)
print(f"Original String: {str_num}, Converted Integer: {int_num}")
Output:
Original String: 789, Converted Integer: 789
Keep in mind that using eval()
may have security implications, especially when dealing with untrusted input. Avoid using it with user inputs unless you can guarantee the safety of the input.
Using Ast
Module
The ast
(Abstract Syntax Trees) is a Python module that provides a safer alternative for eval()
evaluating expressions. The ast.literal_eval()
function can be used to safely evaluate literals.
import ast
# Example: Using ast.literal_eval()
str_num = "101"
int_num = ast.literal_eval(str_num)
print(f"Original String: {str_num}, Converted Integer: {int_num}")
Output:
Original String: 101, Converted Integer: 101
ast.literal_eval()
is safer than eval()
because it only evaluates literals and not arbitrary expressions.
Using Python Try-except
When dealing with user input or data from external sources, it’s crucial to handle potential errors gracefully. Using a Python try-except block with int()
is a robust way to convert strings to integers.
# Example: Robust conversion with try-except
str_num = input("Enter a number: ")
try:
int_num = int(str_num)
print(f"Converted Integer: {int_num}")
except ValueError:
print(f"Conversion failed. Please enter a valid integer.")
This ensures that if the user enters a non-numeric string, the program will handle the error and provide a user-friendly message.
Python Map() for Strings to Integers
If you have a list of strings and want to convert all of them to integers, the map() function can be convenient.
# Example 7: Using map() for multiple conversions
str_numbers = ["23", "45", "67"]
int_numbers = list(map(int, str_numbers))
print(f"Original Strings: {str_numbers}, Converted Integers: {int_numbers}")
Output:
Original Strings: ['23', '45', '67'], Converted Integers: [23, 45, 67]
This method is efficient when dealing with iterable data structures.
Using List Comprehension
List comprehensions provide a concise way to convert a list of strings to integers.
# Example 8: Using list comprehension
str_numbers = ["789", "456", "123"]
int_numbers = [int(num) for num in str_numbers]
print(f"Original Strings: {str_numbers}, Converted Integers: {int_numbers}")
Output:
Original Strings: ['789', '456', '123'], Converted Integers: [789, 456, 123]
List comprehensions are readable and efficient for transforming data.
Python String to Integer Conversion Tips
Here are a few tips to help you convert Python strings to integers.
Strings Contain Negative Value
Ensure the minus sign is appropriately placed when converting strings representing negative numbers.
# Example 9: Handle -ve numbers
str_neg_num = "-456"
int_neg_num = int(str_neg_num)
print(f"Original Val: {str_neg_num}, Converted Val: {int_neg_num+1}")
Output:
Original Val: -456, Converted Val: (-456+1)=-455
Handling Different Bases
If your string represents a number in a base other than 10, you can use the int()
function with the optional base
parameter.
# Example 10: Convert from binary (base 2)
str_bin_num = "1010"
int_bin_num = int(str_bin_num, 2)
print(f"Original Val: {str_bin_num}, Converted Val: {int_bin_num+1}")
Output:
Original Val: 1010, Converted Val: (10+1)=11
F-strings to Convert Strings to Integers
Consider using formatted strings (f-strings) when printing or displaying the converted integers for clarity.
# Example 11: Use f-strings for formatting
str_val = "876"
int_val = int(str_val)
print(f"Original Val: {str_val}, Converted Val: {int_val+1}")
Output:
Original Val: 876, Converted Val: (876+1)=877
Error Handling Best Practices
Always add error handling in Python code, especially when dealing with user inputs or external data. This prevents unexpected crashes and provides a better user experience.
A Quick Wrap
This tutorial laid down various methods to convert Python strings to integers. Each method has its use case, and the choice depends on the specific requirements of your program
Whether you prefer int(), ast.literal_eval(), or list comprehensions, these techniques will help you add string-to-integer conversions to your Python programs.
Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.
Happy coding,
TechBeamers.