这很可能是一个愚蠢的问题,但我想知道为什么 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/