Python 2.7和3.3.2,为什么int('0.0')不起作用?

时间:2013-06-17 07:09:10

标签: python string integer type-conversion

正如标题所说,在Python中(我在2.7和3.3.2中尝试过),为什么int('0.0')不起作用?它给出了这个错误:

ValueError: invalid literal for int() with base 10: '0.0'

如果您尝试使用int('0')int(eval('0.0')),则可以使用...

5 个答案:

答案 0 :(得分:17)

来自int上的文档:

int(x=0) -> int or long
int(x, base=10) -> int or long

如果x 不是数字或者给定base,那么x必须是表示给定基数中整数文字的字符串或Unicode对象。

因此,'0.0'是基数为10的无效整数文字。

你需要:

>>> int(float('0.0'))
0

int上的帮助:

>>> print int.__doc__
int(x=0) -> int or long
int(x, base=10) -> int or long

Convert a number or string to an integer, or return 0 if no arguments
are given.  If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead.

If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base.  The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4

答案 1 :(得分:4)

只是因为0.0不是基数10的有效整数。而0是。

了解int() here.

  

int(x,base = 10)

     

将数字或字符串x转换为整数,或返回   如果没有给出参数,则为0。如果x是一个数字,它可以是一个普通的   整数,长整数或浮点数。如果x是浮动的   点,转换截断为零。如果论证是   在整数范围之外,该函数返回一个长对象。

     

如果x不是数字或者给定了base,则x必须是字符串或   Unicode对象,表示基数中的整数文字。   可选地,文字可以在+或 - 之前(没有空格)   之间)和空白包围。 base-n文字由   数字0到n-1,a到z(或A到Z)的值为10到35。   默认基数为10.允许的值为0和2-36。 Base-2,-8,   和-16文字可以选择前缀为0b / 0B,0o / 0O / 0或   0x / 0X,与代码中的整数文字一样。基数0表示解释   字符串完全是一个整数文字,所以实际的基数是2,8,   10或16。

答案 2 :(得分:3)

如果必须,可以使用

int(float('0.0'))

答案 3 :(得分:3)

您要做的是将字符串文字转换为int。 '0.0'无法解析为整数,因为它包含小数点,因此无法解析为整数。

但是,如果你使用

int(0.0)

int(float('0.0'))

它会正确解析。

答案 4 :(得分:1)

您需要使用以下代码将 int 转换为浮点数: test = 0 testrun = float(int(test)) print(testrun) 输出:测试运行 = 0.0

相关问题