Software

How to Convert a String to an Integer in Python

Use int(s) to turn a string into an integer in Python. Bases, prefixes, whitespace, underscores, decimals and invalid input, with outputs from real runs.

Call int() on the string: int("42") returns the integer 42. It ignores surrounding whitespace and accepts a leading + or -. Pass a base for other number systems, such as int("ff", 16) → 255. If the string is not a valid integer, int() raises ValueError, so wrap user input in try/except.

n = int("42")
print(n + 1)   # 43

What int() accepts

These are real outputs from Python 3.14.3:

int('42')                -> 42
int(' 42\n')             -> 42
int('-17')               -> -17
int('+8')                -> 8
int('1_000_000')         -> 1000000
int('12.5')              -> ValueError: invalid literal for int() with base 10: '12.5'
int('')                  -> ValueError: invalid literal for int() with base 10: ''
int('4 2')               -> ValueError: invalid literal for int() with base 10: '4 2'
int('1__0')              -> ValueError: invalid literal for int() with base 10: '1__0'
int('_1')                -> ValueError: invalid literal for int() with base 10: '_1'

Single underscores between digits are allowed (the same rule as in Python source code), but not at the ends or doubled. Leading and trailing whitespace is stripped; whitespace inside the number is an error.

Other bases: binary, octal, hex

The second argument is the base, from 2 to 36. With base 0, Python reads the prefix the way it does in source code:

int('ff', 16)            -> 255
int('0xff', 16)          -> 255
int('1011', 2)           -> 11
int('z', 36)             -> 35
int('0xff', 0)           -> 255
int('0b1011', 0)         -> 11
int('0o17', 0)           -> 15
int('017', 0)            -> ValueError: invalid literal for int() with base 0: '017'
int('10', 37)            -> ValueError: int() base must be >= 2 and <= 36, or 0

Base 0 rejects 017 on purpose: in Python 2 a leading zero meant octal, so Python 3 refuses to guess. Try any combination here; the emulator reproduces CPython’s rules and error messages:

Try itType a string and choose a base to see what int() returns or raises.

int(' 0x1F ', 0) → 31

To check the arithmetic of a base conversion by hand, the hex to decimal and binary to decimal converters show each step.

Decimal strings like “12.5”

int() will not parse a decimal point. Decide what you want:

int(float("12.5"))       -> 12      # truncates toward zero
int("12.5".split(".")[0]) -> 12     # keeps the integer part of the text
round(float("12.5"))     -> 12      # rounds half to even

For money or other exact decimals, use decimal.Decimal("12.5") instead of float.

Handle invalid input safely

def parse_int(text, default=None):
    try:
        return int(text)
    except ValueError:
        return default

parse_int("42")     # 42
parse_int("abc")    # None

Avoid testing with str.isdigit() first: it returns False for "-42" (we checked: '-42'.isdigit() is False) and True for some non-ASCII digit characters, so try/except is both simpler and more accurate.

Good to know

  • No overflow. Python integers are unbounded: int("9" * 50) works.
  • Unicode digits count. int('١٢٣') (Arabic-Indic digits) returned 123 in our run. If you need ASCII digits only, validate with a regular expression such as ^[+-]?\d+$ using the re.ASCII flag.
  • Very long strings are limited. Python caps decimal conversion at 4,300 digits by default to prevent denial-of-service; sys.set_int_max_str_digits() changes it.

Going the other way, joining numbers into a string, is covered in how to convert a list to a string; the C++ equivalents are in the C++ string-to-int guide.

Sources

  1. Built-in functions: int() — Python documentation
  2. Numeric types — int, float, complex — Python documentation

How we made this

Reproduced in a local lab. Every example on this page was run in Python 3.14.3 and the output pasted verbatim. The interactive emulator of int() is checked against a real CPython for 25 inputs in tests/pyint.test.mjs; it does not emulate non-ASCII digits.

Performed by Claude, an AI assistant working in the BinConvert repository (Python 3.14.3), November 16, 2026.

This article was drafted with AI assistance. Every example, calculation and command output on this page was re-run or checked before release; the examples were re-run in Python 3.14.3 and the emulator test passed against CPython. Review: automated test suite and source check, November 16, 2026.

Spotted an error? Tell us and we will correct it.

Copied to clipboard!