作为 float 的字符串的 Python int()

标签 python

这很可能是一个愚蠢的问题,但我想知道为什么 python 不能从实际上是 float 的字符串中生成整数。

>>> int(1.0)
1
>>> int(float('1.0'))
1

但是

>>> int('1.0')
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    int('1.0')
ValueError: invalid literal for int() with base 10: '1.0'

谁能解释一下为什么不能一步完成?

最佳答案

Can anyone clarify why it cant be done in one step?

引用 Python 之禅:Explicit is better than implicit.

I was wondering why python can't make a integer out of a string that is actually a float number.

根据 Python 的哲学,如果一个字符串包含一个 float ,然后您想要将其转换为一个整数,那么您有责任将其拼写出来。该语言不会尝试猜测您的意图。

关于作为 float 的字符串的 Python int(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15132352/

相关文章:

python - pip 无法安装任何东西

python - 类型检查 python?

python - Jinja loop.index 不打印

Python - 如何为 subprocess.run sdterror 输出添加时间戳前缀?

python - tensorflow 和 Pycharm

python - 如何编写 python 脚本来向 Azure DevOps REST API 进行身份验证并获取访问 token ?

Python 队列 - task_done() 的数量

python - PyQt5 : Setting data for a QStandardItem

Python:如何只在 Pandas 列中保留特定值?

python - 找到要使用的图像?