VOOZH about

URL: https://www.analyticsvidhya.com/blog/2024/02/methods-to-convert-string-to-int-in-python/

⇱ Top 6 Ways to Convert String to Int in Python


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

6 Methods to Convert String to Int in Python

Deepsandhya Shukla Last Updated : 20 May, 2025
3 min read

Introduction

Converting a string to an integer is a common task in Python programming. It allows us to manipulate and perform mathematical operations on numeric values stored as strings. This fundamental task opens the gateway to a domain where manipulation and mathematical prowess converge, enabling you to unleash the true potential of your code. In this article, we will explore various methods to convert a string to an integer in Python, along with examples and best practices.

👁 Convert String to Int in Python

Methods to Convert String to Int in Python

Using the int() Function

Python’s most straightforward method of converting string to int uses the int() function. This function takes a string as input and returns the corresponding integer value. Here’s an example:

string_num = "123"
int_num = int(string_num)
print(int_num)

Output

123

Using the ast.literal_eval() Function

Another method to convert a string to an integer is using the ast.literal_eval() function from the ast module. This function evaluates the given string as a Python literal and returns the corresponding value. Here’s an example:

import ast
string_num = "456"
int_num = ast.literal_eval(string_num)
print(int_num)

Output

456

Converting a String with Decimal Points

If the string represents a floating-point number, the float() function can be used to convert it to a float first, and then the int() function can be used to truncate the decimal part. Here’s an example:

string_num = "7.89"
int_num = int(float(string_num))
print(int_num)

Output

7

Using the numpy.astype() Function

If you are working with arrays or matrices, you can use the numpy.astype() function to convert a string to an integer. This function converts the elements of an array to the specified data type. Here’s an example:

import numpy as np
string_num = "101"
int_num = np.array([string_num]).astype(int)
print(int_num)

Output

[101]

Using Regular Expressions

Regular expressions can extract numeric values from a string and convert them to integers. This method is useful when the string contains non-numeric characters that must be removed before conversion. Here’s an example:

import re
string_num = "12abc34"
int_num = int(re.sub("[^0-9]", "", string_num))
print(int_num)

Output

1234

Using Custom Conversion Functions

In some cases, you may need to perform custom conversions based on specific requirements. You can define your own conversion functions to handle such scenarios. Here’s an example:

def custom_conversion(string_num):
    # Custom logic to convert string to int
    return int(string_num)
string_num = "567"
int_num = custom_conversion(string_num)
print(int_num)

Output

567

If you want to learn more about Python, then explore: Introduction to Python.

Here are a few more examples to Convert String to Int in Python

Handling Invalid String Inputs

A ValueError will be raised during conversion if the string contains non-numeric characters. To handle such cases, you can use exception handling. Here’s an example:

string_num = "abc"
try:
    int_num = int(string_num)
    print(int_num)
except ValueError:
    print("Invalid input")

Output

Invalid input

Converting a String with Leading Zeros

The int() function automatically removes the leading zeros when the string starts with one or more zeros. Here’s an example:

string_num = "000456"
int_num = int(string_num)
print(int_num)  # Output: 456

Also read: 5 Methods to Convert List to String Python

Best Practices to Convert String to Int in Python

Here are some best practices and performance considerations to convert string to Int in Python:

Handling Large Numbers

When dealing with large numbers, it is important to ensure that the conversion method can handle them without losing precision. Python’s int() function can handle arbitrarily large integers, making it suitable for such scenarios.

Choosing the Right Conversion Method

The choice of conversion method depends on the specific requirements of your program. Consider factors such as performance, input validation, and handling of non-numeric characters when selecting the appropriate method.

Conclusion

Converting a string to an integer is a fundamental operation in Python programming. This article explored various methods, including using built-in functions, regular expressions, and custom conversion functions. We also discussed examples and best practices for handling scenarios and optimizing performance. You can effectively convert strings to integers in your Python programs by understanding these techniques.

Hope you like the article and now you know how to convert string to int python, with these you will also clear your doubts on string to integer python and now you will be able to convert it.

Also read, Introduction to Strings in Python for beginners

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
👁 Av Logo White

Continue your learning for FREE

Forgot your password?
👁 Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

👁 Popup Banner
👁 AI Popup Banner