conversion
int()
Constructs an integer from a number or string. When x is a string, base selects the numeric base (0 auto-detects from prefix).
int(x=0, base=10) Parameters
| Parameter | Purpose |
|---|---|
| x | Number or string to convert |
| base | Radix 2-36 (or 0 to auto-detect from '0x', '0o', '0b' prefix) |
Examples
int('42') Returns 42
int('ff', 16) Returns 255
int(3.9) Returns 3 (truncates toward zero)
int('0b101', 0) Returns 5
Gotcha
int(3.9) truncates, doesn't round — use round() for rounding. int('3.14') raises ValueError; convert via int(float('3.14')).
Related built-ins
float()
Constructs a floating-point number from a number or string. Accepts 'inf', '-inf', 'nan' (case-insensitive).
str()
Returns a str version of an object. With bytes/bytearray, decodes using encoding.
round()
Rounds a number to ndigits decimal places. When ndigits is None (default), returns an int rounded to nearest integer using banker's rounding.
dict()
Constructs a dictionary from keyword args, another mapping, or an iterable of key/value pairs. Insertion order is preserved (Python 3.7+).