【Python】【基础知识】【内置函数】【int的使用方法】

原英文帮助文档:

class int([x])class int(x, base=10)

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x defines __int__(), int(x) returns x.__int__(). If x defines __trunc__(), it returns x.__trunc__(). 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 <span>int(‘010‘, <span>0)</span></span> is not legal, while int(‘010‘) is, as well as <span>int(‘010‘, <span>8)</span></span>.

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__.

Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.

Changed in version 3.7: x is now a positional-only parameter.

————————(我是分割线)————————

中文解释

返回一个基于数字或字符串 x 构造的整数对象,或者在未给出参数时返回 <span>0</span>。 如果 x 定义了 <span>__int__()</span><span>int(x)</span> 将返回 <span>x.__int__()</span>。 如果 x 定义了 <span>__index__()</span>,它将返回 <span>x.__index__()</span>。 如果 x 定义了 <span>__trunc__()</span>,它将返回 <span>x.__trunc__()</span>。 对于浮点数,它将向零舍入。

如果 x 不是数字,或者有 base 参数,x 必须是字符串、<span>bytes</span>、表示进制为 base 的 整数字面值 的 <span>bytearray</span>实例。该文字前可以有 <span>+</span> 或 <span>-</span> (中间不能有空格),前后可以有空格。一个进制为 n 的数字包含 0 到 n-1 的数,其中 <span>a</span> 到 <span>z</span> (或 <span>a</span> 到 <span>z</span> )表示 10 到 35。默认的 base 为 10 ,允许的进制有 0、2-36。2、8、16 进制的数字可以在代码中用 <span>0b</span>/<span>0b</span> 、 <span>0o</span>/<span>0o</span> 、 <span>0x</span>/<span>0x</span> 前缀来表示。进制为 0 将安照代码的字面量来精确解释,最后的结果会是 2、8、10、16 进制中的一个。所以 <span>int(‘010‘, <span>0)</span></span> 是非法的,但 <span>int(‘010‘)</span> 和 <span>int(‘010‘, <span>8)</span></span>是合法的。

整数类型定义请参阅 数字类型 --- int, float, complex 。

在 3.4 版更改: 如果 base 不是 <span>int</span> 的实例,但 base 对象有 <span>base.__index__</span> 方法,则会调用该方法来获取进制数。以前的版本使用 <span>base.__int__</span> 而不是 <span>base.__index__</span>

在 3.6 版更改: 您可以使用下划线将代码文字中的数字进行分组。

在 3.7 版更改: x 现在只能作为位置参数。

在 3.8 版更改: 如果 <span>__int__()</span> 未定义则回退至 <span>__index__()</span>