English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The int() method returns an integer object from any number or string.
The syntax of the int() method is:
int(x=0, base=10)
The int() method takes two parameters:
x-The number or string to be converted to an integer object.
default parameteris zero.
base-in xthe base of the number.
It can be 0 (code literal) or2-36.
The int() method returns:
Given a number or an integer object in a string, the default base is considered as10
(Without parameters) Returns 0
(If a base is specified)then the specified base (0,}2,8,10,16)Handling strings
# Integer print('int(123) is:123)) # Float print('int(123int(23) is:123int(23)) # String print('int('123) is:123))
When running the program, the output is:
)) is:123. 123 )) is:123int(23. 123 ) is:123 123
1010, int is:1010, 2)) 1010, int is:1010, 2)) # Octal 0o or 0O 12, int is:12, 8)) 12, int is:12, 8)) # Hexadecimal print('For A, int is:', int('A', 16)) print('For 0xA, int is:', int('0xA', 16))
When running the program, the output is:
For1010, int is: 10 For 0b1010, int is: 10 For12, int is: 10 For 0o12, int is: 10 For A, int is: 10 For 0xA, int is: 10
Internally, the int() method calls the __int__() method of the object.
Therefore, even if an object is not a number, it can be converted to an integer object.
You can return numbers by overriding the __index__() and __int__() methods of the class.
These two methods should return the same value because old versions of Python used __int__() and newer Python uses __index__() method.
class Person: age = 23 def __index__(self): return self.age def __int__(self): return self.age person = Person() print('int(person) is:', int(person))
When running the program, the output is:
int(person) is: 23