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

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

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


当前回答

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

>>> 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 file_to_read != " ":

这不会找到空字符串。它找到一个由一个空格组成的字符串。想必这不是你要找的。

听取别人的建议。这不是非常地道的python代码,如果直接遍历文件,就会清楚得多,但我认为这个问题也值得注意。

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

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

我对这个问题的简单解决方法是将我的代码包装在if语句中,利用空字符串不是“真”的事实:

给定这两个输入中的任意一个:

input_string = ""    # works with an empty string
input_string = "25"  # or a number inside a string

你可以使用这个检查安全地处理一个空白字符串:

if input_string:
   number = int(input_string)
else:
   number = None # (or number = 0 if you prefer)

print(number)