Python 3 reference · Built-in Functions

Python int() Function

Convert a number or string to an integer. Floats are truncated toward zero, and strings can be in any base from 2 to 36.

Python 3 Since 3.0

Syntax

int(x=0)
int(x, base=10)

Parameters

ParameterDescription
x optional A number, or a string of digits. Default: 0
base optional The base of a string x, 2–36, or 0 to read a prefix such as 0x. Default: 10

Return value

An int (Python integers have unlimited size).

Examples

Strings and floatsTry it yourself
print(int("42"), int(" -7 "), int(3.99), int(-3.99))
print(int("1_000_000"))

Output

42 -7 3 -3
1000000
Other basesTry it yourself
print(int("ff", 16), int("1010", 2), int("0o17", 0))

Output

255 10 15
Big numbers and roundingTry it yourself
print(2 ** 100)  # no overflow
print(int(round(2.5)), int(round(3.5)))  # round half to even

Output

1267650600228229401496703205376
2 4

Common mistakes

  • int(3.99) is 3: it truncates. Use round() to round, or math.floor() / math.ceil().
  • int("3.5") raises ValueError; use int(float("3.5")) if you really mean to truncate.
  • Converting very long digit strings is limited to 4,300 digits by default (a protection against denial of service); see sys.set_int_max_str_digits().

Version history

VersionChange
Python 3.0Added
Python 3.6Underscores are allowed in numeric strings.
Python 3.11String conversion is limited to 4,300 digits by default.