How to Convert String to Int in Python

Use string-to-integer conversion in Python when you need to turn text input into a numeric value for calculations, comparisons, or data processing.

What you’ll build or solve

You’ll learn how to convert a string to an integer in Python using int(), handle invalid input safely, and work with different number formats.

When this approach works best

This approach is the right choice when the string represents a valid integer.

Common real-world scenarios include:

  • User input from forms
  • Reading files or CSV data
  • API responses
  • CLI arguments
  • Data cleaning

This is a bad idea when the string contains non-numeric characters that cannot be converted.

Prerequisites

You only need:

  • Basic Python syntax
  • Strings and variables
  • Understanding of numbers

Step-by-step instructions

Step 1: Use int() to convert a string

The simplest way is with the built-in int() function.

age = "25"
age_number = int(age)

Now age_number is an integer.

Step 2: Handle invalid input with try/except

If the string is not a valid number, Python raises an error.

value = "abc"

try:
    number = int(value)
except ValueError:
    number = 0

This prevents crashes and provides a fallback.

Step 3: Convert strings with spaces

int() handles leading and trailing spaces.

value = " 42 "
number = int(value)

This works without extra cleanup.

Step 4: Convert different bases

You can convert strings in other number systems.

binary = "101"
number = int(binary, 2)

This converts binary to decimal.

What to look for:

  • int() converts strings to integers
  • Raises ValueError on invalid input
  • Handles whitespace automatically
  • Supports different bases
  • Use error handling for safety

Examples you can copy

Basic conversion

int("100")

With error handling

try:
    int(user_input)
except ValueError:
    pass

Binary conversion

int("1010", 2)

Common mistakes and how to fix them

Mistake 1: Converting non-numeric strings

What the reader might do:

int("hello")

Why it breaks: the string is not a number.

Corrected approach:

Validate or catch the error.

Mistake 2: Forgetting decimal strings

What the reader might do:

int("3.14")

Why it breaks: this is not an integer string.

Corrected approach:

Use float() first, then convert if needed.

Mistake 3: Ignoring user input errors

What the reader might do:

Convert input directly without checks.

Why it breaks: the program can crash.

Corrected approach:

Use try/except.

Troubleshooting

If conversion fails, check the string content.

If decimals appear, use float().

If user input is unreliable, add validation.

If working with other bases, pass the correct base argument.

Quick recap

  • Use int() to convert strings to integers
  • Handle errors with try/except
  • Works with whitespace
  • Supports binary and other bases
  • Validate input before converting