Python int() Function

Converts a string or number to an integer

Usage

The int() function converts the specified value to integer.

A value can be a number or a string, except complex numbers.

You can also specify the base (number formats like binary, hex, octal etc.) of the given value.

Syntax

int(value,base)

Python int() function parameters
ParameterConditionDescription
valueOptionalA number or a string to be converted into an integer.
Default is 0.
baseOptionalThe number format of specified value.
Default is 10. Valid values are 0, 2-36.

Convert a Number to an Integer

Example: Convert a decimal to integer

x = 4.2
print(int(x))	# 4

The int() method does not round the number, it just returns integer part of a decimal number.

Example:

x = 4.99
print(int(x))   # 4

If you omit both the arguments, the value is assumed as 0.

Example:

print(int())   # 0

Convert a String to an Integer

The method can also convert a string to an integer.

Example:

x = '42'
print(int(x))	# 42
x = '1010'
print(int(x))	# 1010

Specify Base

You can also specify the base of the given value. Valid values are 0 and 2–36.

If base is specified, then value must be a string.

Example: int() on binary string

x = '1110'
print(int(x, 2))	# 14

x = '0b1110'
print(int(x, 2))	# 14

Example: int() on octal string

x = '10'
print(int(x, 8))	# 8

x = '0o10'
print(int(x, 8))	# 8

Example: int() on hex string

x = 'F'
print(int(x, 16))	# 15

x = '0xF'
print(int(x, 16))	# 15

If the base is 0, the base used is determined by the format of value.

Example: int() with base 0

x = '0b1110'
print(int(x, 0))	# 14
x = '0o10'
print(int(x, 0))	# 8
x = '0xF'
print(int(x, 0))	# 15