我从我的代码中得到这个错误:

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

这是什么意思?为什么会发生这种情况,我该如何解决呢?


当前回答

这似乎读数有时是一个空字符串,显然会出现错误。 你可以在你的while循环的int(读数)命令之前添加一个额外的检查,比如:

while readings != 0 or readings != '':
    readings = int(readings)

其他回答

当试图将空字符串转换为整数时发生此错误:

>>> int(5)
5
>>> int('5')
5
>>> int('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

这似乎读数有时是一个空字符串,显然会出现错误。 你可以在你的while循环的int(读数)命令之前添加一个额外的检查,比如:

while readings != 0 or readings != '':
    readings = int(readings)

我正在创建一个程序,读取 文件和if文件的第一行 是不是空白,它读下四个 行。计算在 这些线,然后下一条线是 阅读。

像这样的东西应该工作:

for line in infile:
    next_lines = []
    if line.strip():
        for i in xrange(4):
            try:
                next_lines.append(infile.next())
            except StopIteration:
                break
    # Do your calculation with "4 lines" here

以下代码在Python中运行良好:

>>> int('5') # passing the string representation of an integer to `int`
5
>>> float('5.0') # passing the string representation of a float to `float`
5.0
>>> float('5') # passing the string representation of an integer to `float`
5.0
>>> int(5.0) # passing a float to `int`
5
>>> float(5) # passing an integer to `float`
5.0

然而,传递浮点数的字符串表示形式,或任何其他不表示整数的字符串(包括,例如,像"这样的空字符串)将导致ValueError:

>>> int('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
>>> int('5.0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'

要将浮点数的字符串表示形式转换为整数,首先转换为浮点数,然后转换为整数(正如@katyhuff对问题的评论中所解释的那样):

>>> int(float('5.0'))
5

Python会将数字转换为浮点数。简单地先调用float,然后将其转换为int类型就可以了: 输出= int(float(input))