int() is one of Python’s most essential built-in functions — it converts strings, floats, or other numbers to integers, truncating toward zero (floor for positive, ceil for negative) and enabling safe numeric type coercion. In 2026, int() remains critical in data science (pandas/Polars column typing, index conversion, binning), software engineering (input parsing, configuration, binary/hex/oct conversion), and performance-critical code — handling base conversion (binary, hex, octal), rounding behavior, and error cases with clear exceptions. It’s fast, reliable, and vectorized in NumPy/Dask/Polars for large-scale data processing.
Here’s a complete, practical guide to using int() in Python: basic conversion, base handling (2, 8, 16), error handling & safe patterns, real-world patterns (earthquake magnitude binning, ID parsing, time conversion), and modern best practices with type hints, performance, edge cases, and integration with NumPy/Dask/Polars/pandas.
Basic int() usage — convert strings/floats to integers (truncates toward zero).
print(int(3.9)) # 3 (truncates toward zero)
print(int(-3.9)) # -3 (truncates toward zero)
print(int("42")) # 42
print(int(" 100 ")) # 100 (strips whitespace)
print(int(True)) # 1
print(int(False)) # 0
Base conversion — specify base 2, 8, 16 for binary/octal/hex strings.
print(int("1010", 2)) # 10 (binary)
print(int("52", 8)) # 42 (octal)
print(int("2a", 16)) # 42 (hex, case-insensitive)
print(int("0x2a", 0)) # 42 (auto-detects 0x prefix)
print(int("0o52", 0)) # 42 (auto-detects 0o prefix)
print(int("0b1010", 0)) # 10 (auto-detects 0b prefix)
Real-world pattern: earthquake data cleaning — parse magnitudes, IDs, times from strings.
import pandas as pd
# Sample messy DataFrame
df = pd.DataFrame({
'mag_str': ['7.2', '6.8', 'invalid', '5.9', '7'],
'event_id_str': ['us6000abcde', 'us6000fghij', 'us6000klmno', 'us6000pqrst', 'us6000uvwxy'],
'time_str': ['2025-03-01 12:34:56', '2025-03-02 01:23:45', 'invalid']
})
# Safe integer conversion
def safe_int(value, default: int = 0) -> int:
try:
return int(float(value)) # handle floats/strings
except (ValueError, TypeError):
return default
df['mag'] = df['mag_str'].apply(safe_int)
df['event_id'] = df['event_id_str'].apply(lambda x: safe_int(x[2:], 0) if x.startswith('us') else 0)
# Time to epoch (example)
df['time'] = pd.to_datetime(df['time_str'], errors='coerce')
df['time_epoch'] = df['time'].astype('int64') // 10**9 # seconds
print(df[['mag', 'event_id', 'time_epoch']])
Best practices for int() in Python & data workflows. Use int(x) for explicit integer conversion — when you need int result. Modern tip: prefer Polars pl.col('mag_str').cast(pl.Int64) — fast & handles errors; Dask for distributed data. Use pd.to_numeric(errors='coerce') — pandas standard for safe column conversion. Add type hints — def parse_id(s: str) -> int: return int(s[2:]). Handle base conversion — int(hex_str, 16), int(bin_str, 2). Use int(float(x)) — to truncate floats safely. Catch ValueError — for invalid strings. Use int(x, 0) — auto-detect 0x/0o/0b prefixes. Use int() in binning — int(mag) for magnitude categories. Profile performance — int() is fast; vectorize with NumPy/Polars. Use np.int64/np.int32 — explicit dtype in arrays. Use int.from_bytes() — bytes to int conversion. Use int.bit_length() — bit length of integer. Use int.bit_count() — number of 1 bits (Python 3.10+). Use int.to_bytes() — int to bytes. Use int.as_integer_ratio() — exact fraction representation. Use int.denominator/numerator — after as_integer_ratio().
int() converts strings/numbers to integers — truncates floats, parses bases (2/8/10/16), handles errors gracefully. In 2026, use with pd.to_numeric/Polars casting for data cleaning, NumPy/Dask for vectorization, and safe wrappers for user input. Master int(), and you’ll handle numeric type conversion cleanly and efficiently in any Python workflow.
Next time you need an integer — use int(). It’s Python’s cleanest way to say: “Turn this into a whole number — safely and reliably.”