python3 int(param1, param2) 中的第二个参数设置为 0 时是什么意思?

What does second parameter in python3 int(param1, param2) mean when it is set to 0?

我正在阅读有关 Python 3 int(...) function 的文档,但无法理解以下语句:

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

谁能解释一下它到底在说什么?想不通了。

Python 整数可以用不同的基数表示,方法是给它一个特定的前缀。如果你写 0x16 然后这个数字被解释为十六进制, 0o16 你得到八进制解释等。在源代码中写整数被称为 literal syntax.

您可以将包含使用相同语法的文本的此类字符串值传递给 int() 函数,并通过将第二个参数设置为 [=16= 来让它从此类前缀中找出要使用的基数]:

>>> int('16')       # default base 10
16
>>> int('16', 0)    # no prefix, still base 10
16
>>> int('0x16', 0)  # 0x prefix makes it base 16, hexadecimal
22
>>> int('0o16', 0)  # 0o prefix is interpreted as base 8, octal
14
>>> int('0b101', 0) # 0b prefix means base 2, binary
5

int()0 以外的任何基数都采用零填充字符串:

>>> int('016')
16

但是当您将基数设置为 0 时,此类字符串将不再被接受,因为整数的 Python 文字语法也不接受这些字符串:

>>> int('016', 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 0: '016'

在 Python 2 中,您 可以 像这样使用前导零,这将被解释为八进制数,因此基数为 8。这会导致混淆错误,语法已从 Python 3 中删除,现在仅支持 0o 前缀。