int()的基数为10的文字无效:''

时间:2013-06-04 18:21:23

标签: python int

我遇到了一个问题“使用基数为10的int()的无效文字:''”,这意味着python无法将''转换为整数。但是我已经添加了一个条件if(sh.cell_value(rowx=rx, colx=3)!=''):,它可以跳过excel中不包含任何内容的块。有没有人有一些想法?非常感谢你!

import xlrd
book = xlrd.open_workbook("streeteasy.xls")
sh = book.sheet_by_index(0)
total = 0

for rx in range (sh.nrows):
    if(sh.cell_value(rowx=rx, colx=3)!=''):
        s = sh.cell_value(rowx=rx, colx=3)
        print filter(unicode.isdigit, s)
        print int(filter(unicode.isdigit, s))
        total += int(filter(unicode.isdigit, s))

2 个答案:

答案 0 :(得分:1)

你的if块有缩进,因此是逻辑问题。

更正版本:

for rx in range (sh.nrows):
    if(sh.cell_value(rowx=rx, colx=3)!=''):
        s = sh.cell_value(rowx=rx, colx=3)
        print filter(unicode.isdigit, s)
        print int(filter(unicode.isdigit, s))
        total += int(filter(unicode.isdigit, s))

在您的版本中,只有一个语句位于if块中,其他语句将被执行 即使价值不正确:

for rx in range (sh.nrows):
    if(sh.cell_value(rowx=rx, colx=3)!=''):
        s = sh.cell_value(rowx=rx, colx=3)
    print filter(unicode.isdigit, s)    # THIS IS NOT INSIDE IF
    print int(filter(unicode.isdigit, s))
    total += int(filter(unicode.isdigit, s))

因此,您的代码会在空字符串或不包含数字的字符串上运行。

>>> s = u"      "
>>> 
>>> 
>>> filter(unicode.isdigit, s)
u''
>>> int(filter(unicode.isdigit, s))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

答案 1 :(得分:0)

我建议你这样做。

for rx in range (sh.nrows):
    try:
        s = sh.cell_value(rowx=rx, colx=3)
        total += int(s)
    except ValueError:
        if DEBUG_FLAG:
            debug_print("problem: (%d, %d) is '%s'" % (rx, 3, s))

如果存在空格,则无需从单元格值中删除空格,因为int()可以处理空格。这将处理任何单元格值''或其他任何内容。

我摆脱了filter(),因为我担心它可能会做太多。例如,如果您的某个单元格包含3.1415,那么filter()调用会删除该点,您将获得31415,这似乎不是一个好主意。最好有错误,而不是错误地过滤。

相关问题