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

标签 python python-3.x int literals

我正在阅读有关 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()函数并通过将第二个参数设置为 0 来让它从这样的前缀中找出要使用的基数:

>>> 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现在支持前缀。

关于python - python3 int(param1, param2) 中的第二个参数设置为 0 时是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31056241/

相关文章:

python - 使用 ftplib 访问 FTP URL

c++ - 从类型 char 转换为 int 产生不同的结果

C++ int 出现次数未知范围

c++ 当我将字符串转换为 int 时,int 只是一个随机数?

python - 从 DateTime 数据框列中提取时间并使用线图绘制每小时时间

python - 文件夹存在时 os.path.isdir 返回 false?

python - pandas.concat() 不填充列

python - 如何使用 lambda 搜索多个单词

python - 如果 jinja 标记是字符串格式,我如何在 django 和 jinja2 中使用它?

python - 在列表中存储模数