Sau*_*tro 12 python string integer type-conversion
正如标题所说,在Python中(我试过2.7和3.3.2),为什么int('0.0')
不起作用?它给出了这个错误:
ValueError: invalid literal for int() with base 10: '0.0'
Run Code Online (Sandbox Code Playgroud)
如果你尝试int('0')
或int(eval('0.0'))
它的工作......
Ash*_*ary 17
来自以下文档int
:
int(x=0) -> int or long
int(x, base=10) -> int or long
Run Code Online (Sandbox Code Playgroud)
如果x 不是数字或者给定了base,则x必须是表示给定基数中的整数文字的字符串或Unicode对象.
因此,'0.0'
基数为10的整数文字无效.
你需要:
>>> int(float('0.0'))
0
Run Code Online (Sandbox Code Playgroud)
帮助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
Run Code Online (Sandbox Code Playgroud)
仅仅是因为0.0
不是以 10 为底的有效整数。0
而是。
整数(x,基数=10)
将数字或字符串 x 转换为整数,如果没有给出参数,则返回 0。如果 x 是数字,则它可以是普通整数、长整数或浮点数。如果 x 是浮点数,则转换会向零截断。如果参数在整数范围之外,则该函数返回一个长对象。
如果 x 不是数字或给定了基数,则 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。
您想要做的是将字符串文字转换为 int。'0.0'
无法解析为整数,因为它包含小数点,因此无法解析为整数。
但是,如果您使用
int(0.0)
Run Code Online (Sandbox Code Playgroud)
或者
int(float('0.0'))
Run Code Online (Sandbox Code Playgroud)
它会正确解析。