Tutorial

How To Convert Strings to Integers in Python 3

Guide: how to convert string to int in Python using int(), handling commas, different bases, user input, and error handling.

Drake Nguyen

Founder · System Architect

3 min read
How To Convert Strings to Integers in Python 3
How To Convert Strings to Integers in Python 3

Convert string to int in Python

The simplest way to convert string to int python is to use the built-in int() function. It parses a numeric string and returns an integer, enabling math operations and type casting in Python programs.

Why conversion matters

If numeric values are stored as strings, arithmetic operations will fail. For example, subtracting two string values raises a TypeError because the subtraction operator does not support operands of type str.

# Problem: strings instead of integers
lines_yesterday = "50"
lines_today = "108"

lines_more = lines_today - lines_yesterday
print(lines_more)

# TypeError: unsupported operand type(s) for -: 'str' and 'str'

Basic conversion with int()

Use int() to convert each string before performing arithmetic. This is the most common python string to int conversion method.

# Convert strings to integers using int()
lines_yesterday = "50"
lines_today = "108"

lines_more = int(lines_today) - int(lines_yesterday)
print(lines_more)  # 58

Common conversion scenarios

  • Numeric string with whitespace: trim whitespace then cast.

    value = "  42 \n"
    number = int(value.strip())
  • Strings containing commas: remove commas before conversion.

    big = "1,234,567"
    number = int(big.replace(",", ""))  # 1234567
  • Convert with a specific base: parse binary, hex, or other bases using the base parameter.

    hex_str = "ff"
    number = int(hex_str, 16)  # 255
    binary = int("1010", 2)  # 10

Handling errors and invalid input

Calling int() on an invalid string raises a ValueError (for example, int('abc')). Use a try/except block or validate the string first to safely convert.

# Safe conversion with try/except
def to_int(s):
    try:
        return int(s)
    except ValueError:
        return None  # or handle error as needed

print(to_int("123"))   # 123
print(to_int("12a"))   # None

Converting user input

When converting input from users (which is always a string), validate or catch exceptions to prevent crashes.

# Convert user input to int in Python
raw = input("Enter a number: ")
try:
    value = int(raw.strip().replace(",", ""))
    print("You entered:", value)
except ValueError:
    print("Please enter a valid integer.")

Tips and related concepts

  • Remember the base parameter of int() when parsing non-decimal strings.

  • Watch for ValueError: invalid literal for int() when the string isn’t a valid number.

  • Type casting in Python also includes float() and other data type conversion techniques when dealing with decimals.

Using int() is the idiomatic way to convert numeric strings to integers in Python. Combine it with validation and error handling to make your code robust.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.