Parse decimal input
Convert user or configuration text such as "42" into an integer before arithmetic or validation.
Python · Class
int() creates an integer from a number or string, or returns 0 with no arguments. For strings, base controls parsing, including automatic prefix-based parsing with base=0.
Call int() with no arguments for 0, with a number to convert it to an integer, or with a string and base to parse text in that numeral system. A string may include surrounding whitespace and underscores; when base is 0, Python detects prefixes such as 0x and 0b.
class int(string, /, base=10)| Name | Type | Description |
|---|---|---|
string | number or string | A number or string to convert; omitted to obtain 0. For string input, it may contain a sign, whitespace, and digit separators. |
base | integer | The numeral base for string conversion; defaults to 10 and may be 0 or 2 through 36. |
An integer object, or 0 when called without arguments.
value = int("101", base=2)
print(value) # 5Converts a binary string to an integer.
Convert user or configuration text such as "42" into an integer before arithmetic or validation.
Decode protocol fields, identifiers, or command-line values represented in binary, octal, or hexadecimal text.
Interpret prefixed literals such as 0x10 and 0b101 using their notation.
int() constructs an integer from a number or string, and with no arguments it returns 0. For string input, base defaults to 10 unless supplied.
Follow-up: How would you parse a hexadecimal string with a prefix? Use int(text, 0) when the text follows Python integer-literal conventions, or int(text, 16) for an explicitly hexadecimal input.
The base argument selects the numeral system for string conversion. It can be 0 or an integer from 2 through 36.
Follow-up: Why use base 0? It lets prefixes such as 0x and 0b determine the base, but the input must follow literal-style rules.
For numeric input, int() produces an integer representation; for example, int(123.45) produces 123. String input can contain surrounding whitespace and underscores.
Follow-up: What protocol can a custom object provide? Defining __int__() lets int(x) obtain the conversion from x.__int__().
boolfloatstr__int__