Skip to main content
 首页 » 编程设计

python之int() 不适用于花车

2025年05月04日9dflying

我最近在 Python 3.5 中遇到了这个问题:

>>> flt = '3.14' 
>>> integer = '5' 
>>> float(integer) 
5.0 
>>> float(flt) 
3.14 
>>> int(integer) 
5 
>>> int(flt) 
Traceback (most recent call last): 
  File "<pyshell#7>", line 1, in <module> 
    int(flt) 
ValueError: invalid literal for int() with base 10: '3.14' 

这是为什么?它似乎应该返回 3。我做错了什么,还是有充分的理由发生这种情况?

请您参考如下方法:

int() 需要一个包含整数文字的数字或字符串。根据 Python 3.5.2文档:

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. (Emphasis added)

含义 int() 只能转换包含整数的字符串。您可以轻松地做到这一点:

>>> flt = '3.14' 
>>> int(float(flt)) 
3 

这会将 flt 转换为 float ,然后对 int() 有效,因为它是一个数字。然后它将通过删除小数部分转换为整数。