问题描述
正如标题所说,在 python 中(我在 2.7 和 3.3.2 中尝试过),为什么 int('0.0') 不起作用?它给出了这个错误:
as the title says, in python (i tried in 2.7 and 3.3.2), why int('0.0') does not work? it gives this error:
valueerror: invalid literal for int() with base 10: '0.0'
如果您尝试 int('0') 或 int(eval('0.0')) 它会起作用...
if you try int('0') or int(eval('0.0')) it works...
推荐答案
只是因为 0.0 不是以 10 为底的有效整数.而 0 是.
simply because 0.0 is not a valid integer of base 10. while 0 is.
阅读 int() 这里.
int(x, base=10)
int(x, base=10)
将数字或字符串 x 转换为整数,或返回如果没有给出参数,则为 0.如果 x 是一个数字,它可以是一个普通的整数、长整数或浮点数.如果 x 是浮动的点,转换截断为零.如果论据是在整数范围之外,函数返回一个长对象.
convert a number or string x to an integer, or return 0 if no arguments are given. if x is a number, it can be a plain integer, a long integer, or a floating point number. if x is floating point, the conversion truncates towards zero. if the argument is outside the integer range, the function returns a long object instead.
如果 x 不是一个数字或者如果给出了基数,那么 x 必须是一个字符串或者unicode 对象,表示以基数为基础的整数文字.可选地,文字可以在前面加上 或 - (中间没有空格之间)并被空格包围.一个 base-n 文字由数字 0 到 n-1,其中 a 到 z(或 a 到 z)的值是 10 到 35.默认基数为 10.允许的值为 0 和 2-36.基数 2,-8,和 -16 字面值可以选择以 0b/0b、0o/0o/0 或0x/0x,与代码中的整数文字一样.base 0 表示解释字符串与整数文字完全一样,因此实际基数为 2、8、10 或 16.
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 radix base. optionally, the literal can be preceded by or - (with no space in between) and surrounded by whitespace. a base-n literal consists of the digits 0 to n-1, with a to z (or a to z) having values 10 to 35. the default base is 10. the allowed values are 0 and 2-36. base-2, -8, and -16 literals can be optionally prefixed with 0b/0b, 0o/0o/0, or 0x/0x, as with integer literals in code. base 0 means to interpret the string exactly as an integer literal, so that the actual base is 2, 8, 10, or 16.