TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: How to Convert a Python String to an Integer
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

How to Convert a Python String to an Integer

Last updated: Jun 02, 2024 11:10 pm
By Meenakshi Agarwal
Share
7 Min Read
Python Strings to Integers - Check Out Practical Examples
SHARE

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.

Contents
Python Methods to Convert Str to IntUsing Int() FunctionUsing Float() and Round()Using Eval() to Convert String to IntegerUsing Ast ModuleUsing Python Try-exceptPython Map() for Strings to IntegersUsing List ComprehensionPython String to Integer Conversion TipsStrings Contain Negative ValueHandling Different BasesF-strings to Convert Strings to IntegersError Handling Best PracticesA Quick Wrap

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.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Generate random characters in JavaScript Generate Random Characters With JavaScript Math & Crypto Modules
Next Article DateTime format in Python with Examples Beginner’s Guide to Datetime Format in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x