Python int() function returns an integer object from the specified input. The returned int object will always be in base 10.
Python int()
Python int() function syntax is:
1 2 3 |
class int(x=0, base=10) |
Some important points for int() function are:
- If no argument is provided, 0 will be returned by the int() function.
- If integer literal argument is provided, base should not be provided. The returned int object will be in decimal even if the argument is in hexadecimal, binary or any other base.
- For floating point argument, decimal point will be truncated and int value will be returned. There will be no rounding performed.
- If the argument is string, it will be converted to int. If the string argument is not in base 10, then base must be provided.
- Base argument can be provided for string, bytes and bytearray argument only. The allowed values are 0 and 2 to 36.
- We can use int() with custom object too, in that case object __int__() function will be called. If __int__() function is not defined, then __trunc__() function will be called. If none of them are defined, then
TypeError
will be thrown.
Let’s look into int() function examples with different types of input arguments.
Python int() with numbers
1 2 3 4 5 6 7 |
x = int() print(type(x)) print(x) print(int(0xF)) print(int(0b111)) |
Output:
1 2 3 4 5 |
<class 'int'> 15 7 |
Python int() with float
1 2 3 4 5 6 |
x = int(10.043) print(x) x = int(10.8901) print(x) |
Output:
1 2 3 4 |
10 10 |
Notice that integer part of floating point number is returned, no rounding is performed.
Python int() with string
1 2 3 4 5 6 7 8 |
x = int("5") print(x) x = int("-0xf", base=16) print(x) x = int("0b111", base=2) print(x) |
Output:
1 2 3 4 5 |
5 -15 7 |
Python int() with bytes and bytearray
1 2 3 4 5 6 |
x = int(bytes("-0xf", "utf-8"), 16) print(x) x = int(bytearray("-20", "utf-8")) print(x) |
Output:
1 2 3 4 |
-15 -20 |
Python int() with custom object
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Emp: id = 0 def __int__(self): print('__int__ function called') return self.id def __trunc__(self): print('__trunc__ function called') return self.id x = Emp() x.id = 100 print(int(x)) |
Output:
1 2 3 4 |
__int__ function called 100 |
If we comment __int__ function, then the output will be:
1 2 3 4 |
__trunc__ function called 100 |
If we comment both __int__ and __trunc__ functions, then we get the following error.
1 2 3 |
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Emp' |
Summary
Python int() function is used to convert string, bytes, bytearray and objects to an int object. The integer is always returned in base 10. We can get the same value by directly calling object.__int__()
function.
Reference: Official Documentation