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)
Parameter | Condition | Description |
value | Optional | A number or a string to be converted into an integer. Default is 0. |
base | Optional | The number format of specified value. Default is 10. Valid values are 0, 2-36. |
Convert a Number to an Integer
x = 4.2
print(int(x))
# Prints 4
The int()
method does not round the number, it just returns integer part of a decimal number.
x = 4.99
print(int(x))
# Prints 4
If you omit both the arguments, the value is assumed as 0.
print(int())
# Prints 0
Convert a String to an Integer
The method can also convert a string to an integer.
x = '42'
print(int(x))
# Prints 42
x = '1010'
print(int(x))
# Prints 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.
# binary string
x = '1110'
print(int(x, 2))
# Prints 14
x = '0b1110'
print(int(x, 2))
# Prints 14
# octal string
x = '10'
print(int(x, 8))
# Prints 8
x = '0o10'
print(int(x, 8))
# Prints 8
# hex string
x = 'F'
print(int(x, 16))
# Prints 15
x = '0xF'
print(int(x, 16))
# Prints 15
If the base is 0
, the base used is determined by the format of value.
x = '0b1110'
print(int(x, 0))
# Prints 14
x = '0o10'
print(int(x, 0))
# Prints 8
x = '0xF'
print(int(x, 0))
# Prints 15