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

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

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


当前回答

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

我的原始错误类似于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")

其他回答

错误消息意味着提供给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

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

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

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

>>> 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: ''

当您必须将空格分隔的整数映射到一个列表,但您使用.input()逐行输入整数时,也会发生这种情况。 例如,我在HackerRank Bon-Appetit上解决这个问题,在编译时得到了以下错误

因此,不要逐行向程序输入,而是尝试使用map()方法将空格分隔的整数映射到列表中。