Back to Blog
Python

Python String to Int Conversion with int()

python string to int: Learn how to convert strings to integers in Python using int(), handle invalid input with ValueError, custom bases, and practical edge cases.

Pythontype-conversionerror-handlinginput-parsingint-function
An illustration showing a string of text characters transforming into a solid integer block with an arrow, representing the int() conversion in Python.

The core of python string to int conversion is the built-in int() constructor. When you pass a string to int(), Python parses it as a base-10 integer by default:

value = int("42") print(value) # 42 print(type(value)) # <class 'int'>

This is the most common form of string-to-integer conversion in Python. The int() function accepts a string and returns an integer, but it has specific rules about what it will accept.

How int() Parses a String

When int() receives a string, it follows a precise parsing sequence:

  1. Leading and trailing whitespace is stripped.
  2. An optional sign (+ or -) is allowed.
  3. The remaining characters must form a valid digit sequence for the specified base.
print(int(" 42 ")) # 42 (whitespace stripped) print(int("+42")) # 42 (explicit positive sign) print(int("-42")) # -42 (negative sign)

The whitespace stripping is useful when parsing user input or data files where extra spaces are common. However, int() does not accept internal whitespace:

# Raises ValueError # int("4 2")

Converting with a Custom Base

The int() constructor accepts an optional base argument (2 through 36) that controls how the string is interpreted:

print(int("1010", 2)) # 10 print(int("ff", 16)) # 255 print(int("777", 8)) # 511 print(int("z", 36)) # 35

The base parameter is useful when parsing binary, hexadecimal, or octal data from configuration files, network protocols, or hardware interfaces. When a base other than 10 is specified, the string must contain only valid digits for that base — int("ff", 16) works, but int("ff", 10) raises a ValueError.

Handling Invalid Input

The most common failure mode in python string to int conversion is a ValueError raised when the string does not represent a valid integer. This happens with empty strings, non-numeric characters, decimal points (float strings), and strings that are valid for one base but not another.

def parse_integer(text): try: return int(text) except ValueError: return None

The try/except pattern is the standard way to handle invalid input. It is preferable to pre-validating with methods like str.isdigit() because isdigit() has its own edge cases — it returns True for some Unicode characters that int() cannot parse, and it does not handle signs or whitespace.

Practical Patterns for User Input

When converting user input from input(), command-line arguments, or HTTP query parameters, you typically need to handle invalid values gracefully:

import sys def get_port(): raw = input("Enter port: ") try: port = int(raw) except ValueError: print(f"Invalid port: {raw!r}") sys.exit(1) if not (0 <= port <= 65535): print("Port out of range") sys.exit(1) return port

The !r repr format in the f-string shows the actual string content, which helps debugging when the input contains invisible characters.

Performance Considerations

In performance-sensitive code paths, the try/except pattern has a cost only when the exception is actually raised. For valid input, int() is a C-level operation and is fast. The main performance concern is avoiding repeated conversion attempts on the same data.

If you are parsing a large dataset where most values are valid integers, the try/except approach is appropriate. If you are parsing a stream where many values are invalid, pre-filtering with a cheap check can reduce exception overhead, but you still need try/except as a safety net because no string check perfectly predicts int() behavior.

Edge Cases and Compatibility

Several edge cases are worth knowing.

Unicode digits: int() accepts Unicode decimal digits, not just ASCII:

print(int("٤٢")) # 42 (Arabic-Indic digits)

Bytes input: int() also accepts bytes and bytearray objects, which is useful when parsing binary protocols:

print(int(b"42")) # 42

Float strings: int("3.14") raises ValueError. If you need to convert a string containing a decimal number, you must use float() first:

value = int(float("3.14")) # 3

This truncates toward zero, which may or may not be the behavior you want. For rounding, use round() before converting.

None and other types: int(None) raises TypeError, not ValueError. If your input could be None, check for it explicitly before calling int().

The behavior of int() with strings has been stable across Python 3.x. Python 2's int() had different behavior for very large numbers (returning long), but this is irrelevant for modern Python 3 code.

When Not to Use int()

For some use cases, alternatives are more appropriate:

  • float(): When the string contains a decimal point or exponent notation.
  • Decimal: When you need exact decimal arithmetic and the string represents a monetary value.
  • ast.literal_eval(): When you need to safely evaluate a string that is a Python literal, but this is overkill for simple integers.
  • Regular expressions: When you need to extract integers from within a larger string.
import re text = "The order total is 42 items" match = re.search(r"\d+", text) if match: count = int(match.group())

The regex approach is useful when the integer is embedded in surrounding text, but it is slower than direct int() conversion and should not be used when the string is already a clean integer representation.

A Complete Parsing Function

Combining the patterns above, here is a robust integer parser that handles the common production cases:

def parse_int(value, default=None, base=10): """Parse a string as an integer with a fallback default.""" if value is None: return default if isinstance(value, int): return value if isinstance(value, (bytes, bytearray)): value = value.decode("ascii", errors="ignore") if not isinstance(value, str): return default try: return int(value.strip(), base) except ValueError: return default

This function handles None, already-integer inputs, bytes input, whitespace, and invalid strings. The default parameter lets callers decide what to return on failure rather than forcing an exception. This is a common pattern in configuration parsing and data-cleaning pipelines where missing or malformed fields should not crash the entire process.

python string to int: Practical Usage and Code Examples | RYUSLOG DEV