【问题标题】:Python 2.7 and 3.3.2, why int('0.0') does not work?Python 2.7 和 3.3.2,为什么 int('0.0') 不起作用?
【发布时间】:2013-06-13 02:04:17
【问题描述】:

正如标题所说,在 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')),它会起作用...

【问题讨论】:

    标签: python string integer type-conversion


    【解决方案1】:

    来自int 上的文档:

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

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

    所以,'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
    

    【讨论】:

      【解决方案2】:

      仅仅是因为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。基数 2,-8, 和 -16 字面值可以选择以 0b/0B、0o/0O/0 或 0x/0X,与代码中的整数文字一样。 Base 0 表示解释 字符串与整数文字完全一样,因此实际基数为 2、8、 10 或 16。

      【讨论】:

        【解决方案3】:

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

        但是,如果你使用

        int(0.0)
        

        或

        int(float('0.0'))
        

        它会正确解析。

        【讨论】:

          【解决方案4】:

          如果你必须,你可以使用

          int(float('0.0'))
          

          【讨论】:

            【解决方案5】:

            您需要使用以下代码将 int 转换为 float: test = 0 testrun = float(int(test)) print(testrun) 输出:testrun = 0.0

            【讨论】:

            • 不知道怎么用文字转码转换器就这个抱歉!
            • 抱歉让你的脚本运行你将不得不翻转代码。只需使用 int(float(0.0)) 这会将浮点数舍入到最接近的值。输出 0
            • 请注意 int 是整数 0、1、2、3 等。浮点数是小数点 0.0、1.0、2.0 等的数字。如果我们想在我们需要将 flot 转换为 int 的位置,反之亦然
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-09-14
            • 1970-01-01
            相关资源
            最近更新 更多