参数形式
- int(x=0)
- int(x, base=10)
Manual
Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. The default base is 10. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int(‘010’, 0) is not legal, while int(‘010’) is, as well as int(‘010’, 8).
The integer type is described in Numeric Types — int, float, complex.
Changed in version 3.4: If base is not an instance of int and the base object has a base.__index__ method, that method is called to obtain an integer for the base. Previous versions used base.__int__ instead of base.__index__.
直译
根据数字或字符串x构造一个整数对象,若未给定参数则返回0。如果x是数字,则返回x.__int__()。对于浮点数,会直接截断为0。
如果x是非数值或给定base,那么x必须是在其基数base上,可以用来表示整数字面的string、bytes或bytearray的实例。字面可以选择+或-(中间不空格)做前缀,由空格环绕。n位基数字面包含数字0到n-1,同时a到z(或A到Z)表示的值为10到35。默认的base是10,其允许的值域为0和2-36。如同代码中的整数字面,基数2、8和16位字面可选用0b/0B、0o/0O或0x/0X作为前缀。基数0表示精确的解释成一个代码字面,那么实际中的基数是2、8、10或16,以致于int(‘010’, 0)是非法的,然而int(‘010’)等同于int(‘010’, 8)。
整数类型详情见数字类型 — 整数、浮点数和复数。
version 3.4变更:如果base不是整数实例,且base对象有base.__index__方法,那么会调用该方法来获取一个整数,前一个版本使用的是base.__int__。
实例
# 字符串
>>> int('10')
10
# 浮点数
>>> int(3.14)
3
# bytes对象
>>> int(b'10')
10
# 16进制
>>> int('0xa', 16)
10
# 8进制
>>> int('0o12', 8)
10
# 2进制
>>> int('1010', 2)
10