How to Convert a String to an Integer in Python?

In this tutorial, I will explain how to convert a string to an integer in Python. As a programmer, I recently encountered a situation where I needed to convert user input, which is always a string, into an integer for further processing. I explored more about this topic and found five efficient ways to achieve this task. Let us learn all the methods with suitable examples.

Convert a String to an Integer in Python

Python provides ways to convert a string to an integer. Let us see some important methods.

Read How to Get the Last 3 Characters of a String in Python?

Method 1. Use Python int() Function

The int() function is the most common and simple way to convert a string to an integer. If the string contains valid numeric data, int() will return the corresponding integer.

name = "Washington"
string_number = "1234"
converted_number = int(string_number)
print(converted_number)  

Output:

1234

I have executed the above example code and added the screenshot below.

Convert a String to an Integer in Python

The int() constructor converts the string "1234" into the integer 1234. It only works if the string is a valid representation of an integer.

Check out How to Get the Last 4 Characters of a String in Python?

Method 2. Use isdigit() Method

You can first check whether a string consists of digits using the isdigit() method, and then convert it to an integer using int(). This prevents errors if the string is not a valid number.

name = "Chicago"
string_number = "5678"

if string_number.isdigit():
    converted_number = int(string_number)
    print(converted_number) 
else:
    print("Invalid input")

Output:

5678

I have executed the above example code and added the screenshot below.

How to Convert a String to an Integer in Python

TThe isdigit() method checks if the string consists only of digits. If true, the string is safely converted into an integer.

Read How to Truncate a String to a Specific Length in Python?

Method 3. Use ast.literal_eval() Method

The ast.literal_eval() function is a safer alternative eval() when you want to evaluate a string containing a Python literal (e.g., numbers, lists, dictionaries). It only evaluates safe literals and won’t execute arbitrary code.

import ast

name = "Los Angeles"
string_number = "9876"

converted_number = ast.literal_eval(string_number)
print(converted_number)  

Output:

9876

I have executed the above example code and added the screenshot below.

Convert a String to an Integer in Python ast.literal_eval()

ast.literal_eval() safely evaluates the string "9876" as an integer. This is a more secure option compared to eval() , as it only allows Python literals and not arbitrary code execution.

Check out How to Print Strings and Integers Together in Python?

Method 4. Use eval() Function

The eval() function evaluates the string as a Python expression and converts it into the corresponding value. While it can be used for conversion, it should be used with caution due to security risks if the input is untrusted.

name = "San Francisco"
string_number = "4321"

converted_number = eval(string_number)
print(converted_number)

Output:

4321

Here, eval() evaluates the string "4321" and returns it as an integer. While it works, using eval() is generally not recommended for user input, as it can execute arbitrary code.

Read How to Convert a String to Date in Python?

Method 5. Use Try-Except Block to Handle Exceptions

Using a try-except block allows you to handle cases where the string might not be a valid integer and avoid program crashes.

name = "Dallas"
string_number = "invalid_number"

try:
    converted_number = int(string_number)
    print(converted_number)
except ValueError:
    print("The input is not a valid integer")

Output:

1234

If the string is not a valid integer, a ValueError will be raised, and the exception handling will print the appropriate error message. This ensures that the program doesn’t crash unexpectedly.

Check out How to Find the Second Occurrence of a Substring in a Python String?

Conclusion

In this tutorial, I have explained how to convert a string to an integer in Python. I discussed some important methods like using the int() method, isdigit() method, ast.literal_eval() method, eval() function, and try-except block to handle exceptions.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.