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

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

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


当前回答

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

readings = int(readings)

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

其他回答

这似乎读数有时是一个空字符串,显然会出现错误。 你可以在你的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: ''

错误消息意味着提供给int的字符串不能被解析为整数。在:后面的部分显示了所提供的字符串。

在问题中描述的情况下,输入是一个空字符串,写为“。

下面是另一个例子——表示浮点值的字符串不能直接用int转换:

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

相反,先转换为float:

>>> int(float('55063.000000'))
55063

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

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

或者使用异常处理:

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

以下代码在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