Rolex Pearlmaster Replica
  Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
This article is part of in the series
Published: Wednesday 12th February 2025
Last Updated: Wednesday 5th March 2025

how to convert string to integer with Python

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.

Latest Articles


Tags

  • deque
  • heap
  • Data Structure
  • howto
  • dict
  • csv in python
  • logging in python
  • Python Counter
  • python subprocess
  • numpy module
  • Python code generators
  • KMS
  • Office
  • modules
  • web scraping
  • scalable
  • pipx
  • templates
  • python not
  • pytesseract
  • env
  • push
  • search
  • Node
  • python tutorial
  • dictionary
  • csv file python
  • python logging
  • Counter class
  • Python assert
  • linspace
  • numbers_list
  • Tool
  • Key
  • automation
  • website data
  • autoscale
  • packages
  • snusbase
  • boolean
  • ocr
  • pyside6
  • pop
  • binary search
  • Insert Node
  • Python tips
  • python dictionary
  • Python's Built-in CSV Library
  • logging APIs
  • Constructing Counters
  • Assertions
  • Matplotlib Plotting
  • any() Function
  • Activation
  • Patch
  • threading
  • scrapy
  • game analysis
  • dependencies
  • security
  • not operation
  • pdf
  • build gui
  • dequeue
  • linear search
  • Add Node
  • Python tools
  • function
  • python update
  • logging module
  • Concatenate Data Frames
  • python comments
  • matplotlib
  • Recursion Limit
  • License
  • Pirated
  • square root
  • website extract python
  • steamspy
  • processing
  • cybersecurity
  • variable
  • image processing
  • incrementing
  • Data structures
  • algorithm
  • Print Node
  • installation
  • python function
  • pandas installation
  • Zen of Python
  • concatenation
  • Echo Client
  • Pygame
  • NumPy Pad()
  • Unlock
  • Bypass
  • pytorch
  • zipp
  • steam
  • multiprocessing
  • type hinting
  • global
  • argh
  • c vs python
  • Python
  • stacks
  • Sort
  • algorithms
  • install python
  • Scopes
  • how to install pandas
  • Philosophy of Programming
  • concat() function
  • Socket State
  • % Operator
  • Python YAML
  • Crack
  • Reddit
  • lightning
  • zip files
  • python reduce
  • library
  • dynamic
  • local
  • command line
  • define function
  • Pickle
  • enqueue
  • ascending
  • remove a node
  • Django
  • function scope
  • Tuple in Python
  • pandas groupby
  • pyenv
  • socket programming
  • Python Modulo
  • Dictionary Update()
  • Hack
  • sdk
  • python automation
  • main
  • reduce
  • typing
  • ord
  • print
  • network
  • matplotlib inline
  • Pickling
  • datastructure
  • bubble sort
  • find a node
  • Flask
  • calling function
  • tuple
  • GroupBy method
  • Pythonbrew
  • Np.Arange()
  • Modulo Operator
  • Python Or Operator
  • Keygen
  • cloud
  • pyautogui
  • python main
  • reduce function
  • type hints
  • python ord
  • format
  • python socket
  • jupyter
  • Unpickling
  • array
  • sorting
  • reversal
  • Python salaries
  • list sort
  • Pip
  • .groupby()
  • pyenv global
  • NumPy arrays
  • Modulo
  • OpenCV
  • Torrent
  • data
  • int function
  • file conversion
  • calculus
  • python typing
  • encryption
  • strings
  • big o calculator
  • gamin
  • HTML
  • list
  • insertion sort
  • in place reversal
  • learn python
  • String
  • python packages
  • FastAPI
  • argparse
  • zeros() function
  • AWS Lambda
  • Scikit Learn
  • Free
  • classes
  • turtle
  • convert file
  • abs()
  • python do while
  • set operations
  • data visualization
  • efficient coding
  • data analysis
  • HTML Parser
  • circular queue
  • effiiciency
  • Learning
  • windows
  • reverse
  • Python IDE
  • python maps
  • dataframes
  • Num Py Zeros
  • Python Lists
  • Fprintf
  • Version
  • immutable
  • python turtle
  • pandoc
  • semantic kernel
  • do while
  • set
  • tabulate
  • optimize code
  • object oriented
  • HTML Extraction
  • head
  • selection sort
  • Programming
  • install python on windows
  • reverse string
  • python Code Editors
  • Pytest
  • pandas.reset_index
  • NumPy
  • Infinite Numbers in Python
  • Python Readlines()
  • Trial
  • youtube
  • interactive
  • deep
  • kernel
  • while loop
  • union
  • tutorials
  • audio
  • github
  • Parsing
  • tail
  • merge sort
  • Programming language
  • remove python
  • concatenate string
  • Code Editors
  • unittest
  • reset_index()
  • Train Test Split
  • Local Testing Server
  • Python Input
  • Studio
  • excel
  • sgd
  • deeplearning
  • pandas
  • class python
  • intersection
  • logic
  • pydub
  • git
  • Scrapping
  • priority queue
  • quick sort
  • web development
  • uninstall python
  • python string
  • code interface
  • PyUnit
  • round numbers
  • train_test_split()
  • Flask module
  • Software
  • FL
  • llm
  • data science
  • testing
  • pathlib
  • oop
  • gui
  • visualization
  • audio edit
  • requests
  • stack
  • min heap
  • Linked List
  • machine learning
  • scripts
  • compare string
  • time delay
  • PythonZip
  • pandas dataframes
  • arange() method
  • SQLAlchemy
  • Activator
  • Music
  • AI
  • ML
  • import
  • file
  • jinja
  • pysimplegui
  • notebook
  • decouple
  • queue
  • heapify
  • Singly Linked List
  • intro
  • python scripts
  • learning python
  • python bugs
  • ZipFunction
  • plus equals
  • np.linspace
  • SQLAlchemy advance
  • Download
  • No
  • nlp
  • machiine learning
  • dask
  • file management
  • jinja2
  • ui
  • tdqm
  • configuration
  • Python is a beautiful language.