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

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

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


当前回答

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

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

其他回答

Int不能将空字符串转换为整数。如果输入字符串可以是空的,考虑检查这种情况:

if data:
    as_int = int(data)
else:
    # do something else

或者使用异常处理:

try:
    as_int = int(data)
except ValueError:
    # do something else

另一个答案,以防以上所有的解决方案都不适合你。

我的原始错误类似于OP: ValueError: invalid literal for int() with base 10: '52,002'

然后,我尝试了接受的答案,得到了这个错误:ValueError:无法将字符串转换为浮动:' 52002 '——这是当我尝试int(float(variable_name))时

我的解决方案是将字符串转换为浮点数,并将其留在那里。我只是需要检查是否字符串是一个数值,这样我就可以正确地处理它。

try: 
   float(variable_name)
except ValueError:
   print("The value you entered was not a number, please enter a different number")

我正在创建一个程序,读取 文件和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

我最近遇到了一个案例,这些答案都不管用。我遇到的CSV数据中混合了空字节,这些空字节没有被剥离。所以,我的数字字符串,剥离后,由这样的字节组成:

\x00\x31\x00\x0d\x00

为了解决这个问题,我做了:

countStr = fields[3].replace('\x00', '').strip()
count = int(countStr)

...其中fields是分隔行产生的CSV值列表。

因为这一行,你的答案是抛出错误

readings = int(readings)

在这里,您试图将字符串转换为int类型,而不是以10为基数。你只能将一个以10为基数的字符串转换为int,否则它将抛出ValueError,声明以10为基数的int()的无效字面量。