PyPython example

How to convert a string to an int in Python

5 min read▶ Runs in an isolated hosted runtimeUpdated Jul 2026

Quick answer

Pass the string to the built-in int(): int("42") returns the integer 42. It tolerates surrounding whitespace and a leading sign, and raises ValueError on anything it can't parse — so wrap it in try/except whenever the string came from a user.

int() is strict on purpose: it parses a whole number and nothing else. A stray "3.5", an empty string, or a rogue letter is an error, not a best guess. That strictness is a feature — it just means real code needs a plan for the failure case. Each example below runs on this page: hit Run, then edit the code and run it again.

1The int() built-inRecommended

int(text) parses a decimal integer and hands back a real int you can do arithmetic with. Leading and trailing whitespace is stripped for you, and a leading - or + is honoured.

int_basic.py

Output

Prints 42 <class 'int'>, then 50, then -7. Note that number + 8 gives 50, not "428" — that concatenation is exactly the bug the conversion exists to prevent.

2Handle bad input with try/except

Anything int() can't parse raises ValueError, and a None raises TypeError. Since user input, CSV cells and query strings are never trustworthy, the real-world shape is a small helper that catches both and returns a default. The tempting alternative — check first with .isdigit() — is printed alongside so you can see it disagree.

safe_int.py

Output

The check is wrong in both directions. It rejects "+5", which int() happily parses as 5, because lstrip("-") knows nothing about a leading plus. And it accepts "²" str.isdigit() is true for superscripts and other Unicode digit characters that int() flatly refuses. Catching the exception is the only check that agrees with the parser, because it is the parser.

3Strings with a decimal point

int("3.5") does not round — it raises ValueError: invalid literal for int() with base 10: '3.5'. Go through float() first. Just know what you're buying: int() truncates toward zero, while round() rounds to nearest and breaks ties toward the even number.

decimals.py

Output

Output: the ValueError message, then 3, -3, 4, 2. Truncation is symmetric around zero — -3.5 becomes -3, not -4. And round(2.5) is 2, not 3: Python uses banker's rounding, so exact .5 ties land on the even integer.

4Binary, hex, and other bases

int() takes a second argument: the base. Pass 2 for binary, 8 for octal, 16 for hex. The matching 0b/0o/0x prefix is optional but allowed. Pass 0 and Python reads the prefix and picks the base itself.

bases.py

Output

Prints 10, 255, 255, 493, then 10 493 255 42. The last line is the catch: with base 0 a string must be a valid Python literal, and "0755" — a C-style octal with no o — isn't one, so it raises invalid literal for int() with base 0: '0755'. If you know the base, say so explicitly.

5Which should you use?

MethodOn bad inputHandles decimalsBest for
int(s)Raises ValueErrorNoInput you already trust
try: int(s) / except ValueErrorYou pick the fallbackNoUser input, files, APIs
int(float(s))Raises ValueErrorYes — truncatesNumeric strings that may hold a dot
int(s, base)Raises ValueErrorNoBinary, octal and hex text
s.strip().lstrip("-").isdigit()Returns FalseNoRough pre-check only — it disagrees with int()

6Common variation: a whole list of strings

For a clean list, map(int, rows) is the shortest thing that works — and it's lazy, so sum(map(int, rows)) never builds the intermediate list. For messy data, map a forgiving helper instead and filter out the misses.

many.py

Output

Prints [1, 2, 3, 4], 10, then [10, 20, 30] 60. Filter on is not None rather than truthiness — "0" converts to 0, which is falsy, and a plain if n would silently drop it.

Frequently asked questions

Why does int("3.5") raise a ValueError in Python?

int() parses a whole number only, so a decimal point is a syntax error to it: ValueError: invalid literal for int() with base 10: '3.5'. Convert through float first — int(float("3.5")) gives 3. Note that it truncates toward zero rather than rounding, so int(float("-3.5")) is -3; use round(float(s)) if you want nearest.

How do I convert a string to an int without crashing on bad input?

Wrap the call: try: return int(value) / except (ValueError, TypeError): return default. ValueError covers unparseable text and TypeError covers None. This is more reliable than validating first, because the exception is raised by the same parser that would do the conversion.

Is isdigit() a reliable way to check a string before converting it?

No. str.isdigit() is true for superscripts like "²" that int() rejects, and false for strings int() accepts such as "+5" and "1_000". It also returns true for non-ASCII digits like Arabic-Indic "١٢٣", which int() converts to 123. Use try/except ValueError instead.

How do I convert a hex or binary string to an int?

Pass the base as the second argument: int("ff", 16) is 255 and int("1010", 2) is 10. The 0x / 0b / 0o prefixes are optional when you name the base. Passing base 0 auto-detects from the prefix, but then the string must be a valid Python literal — int("0755", 0) raises.