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
| Parameter | Description |
|---|---|
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
print(int("42"), int(" -7 "), int(3.99), int(-3.99))
print(int("1_000_000"))
Output
42 -7 3 -3 1000000
print(int("ff", 16), int("1010", 2), int("0o17", 0))
Output
255 10 15
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)is3: it truncates. Useround()to round, ormath.floor()/math.ceil().int("3.5")raisesValueError; useint(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
| Version | Change |
|---|---|
| Python 3.0 | Added |
| Python 3.6 | Underscores are allowed in numeric strings. |
| Python 3.11 | String conversion is limited to 4,300 digits by default. |
Related
float()· Convert a number or numeric string to a floating-point number. Also understands 'inf', '-inf' and 'nan'.round()· Round a number to a given number of decimal places. Halfway values round to the nearest even number (banker's rounding).bin()· Convert an integer to a binary string prefixed with 0b, such as bin(5) giving '0b101'. Negative numbers get a minus sign.hex()· Convert an integer to a lowercase hexadecimal string prefixed with 0x, such as hex(255) giving '0xff'.str()· Convert a value to its readable text form, or decode bytes into a string. Strings are immutable sequences of characters.- Python Numbers · tutorial
- Python Casting · tutorial