How to Convert String to Int in Python

The fastest way to convert a string to int in Python is the int() function:

numero = int("42")

When do you need this?

When you read data from files or forms, you almost always receive text. Converting types is a fundamental skill in Python: it lets you add numbers, compare values or run calculations. In this guide you will learn how to convert a string to int in Python with int(), how to handle decimals and errors, and how to convert whole lists.

The built-in function int() is the simplest way to convert a string to int in Python.

numero = int("42")
print(numero)        # 42
print(numero + 8)    # 50

If the string contains leading or trailing spaces, int() ignores them.

print(int("  42  "))  # 42

Method 2: Convert from another base

You can convert strings in binary, octal or hexadecimal format by passing the base as the second argument.

print(int("1010", 2))   # 10 (binary)
print(int("1A", 16))    # 26 (hexadecimal)
print(int("17", 8))     # 15 (octal)

Method 3: Convert with float()

If the string has decimals, use float() and then round the result with int().

print(float("3.14"))   # 3.14
print(int(3.99))       # 3

Method 4: Convert a list of strings

With a comprehension you can convert an entire list of strings in one line.

valores = ["10", "20", "30"]
numeros = [int(v) for v in valores]
print(numeros)
# [10, 20, 30]

Method comparison

Method Advantage When to use it
int() Direct and simple Recommended always
int(x, base) Converts other bases Binary, hex or octal
float() Keeps decimals When you need decimals
List comprehension Converts everything Entire lists in one line

Common errors and solutions

ValueError: the string is not a number

If the string is not a valid number, Python raises a ValueError. Use try and except to handle it.

try:
    numero = int("hola")
except ValueError:
    print("No es un número válido")

Trying to convert an empty string

int("") raises a ValueError. Check the value before converting it.

Converting a string with decimals

int("3.14") raises a ValueError. Use float() first and then int() if you need an integer.

Frequently asked questions

What happens if I convert an empty string?

int("") raises a ValueError. You must check the value before converting it.

Can I convert a string with decimals?

Not directly. Use float() first and then int() if you need an integer.

Does int() work with negative numbers?

Yes. int("-10") returns -10.

how to convert string to int in python, string to int python, convertir string a int python, int python, float python, type conversion python, python ValueError

Save this tutorial and share it if it helped you. Find more practical guides in the Python how-to section.