【问题标题】:invalid literal for int() with base 10: ''基数为 10 的 int() 的无效文字:''
【发布时间】:2013-05-31 06:19:28
【问题描述】:

我遇到了一个问题“invalid literal for int() with base 10: ''”,这意味着 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))

【问题讨论】:

  • 如果您引用的错误消息是实际错误消息,则字符串不为空。它包含一个空格。此外,即使您的 if 块没有执行,您仍然会继续循环的其余部分并尝试在 s 上调用 int
  • 检查if string.strip(),这将删除空格...
  • @BrenBarn 除非帖子在您发表评论后得到忍者编辑,否则我认为您误读了。 '' 是空字符串 - 没有空格。
  • @sgpc 我添加了 .strip() 之类的:print int(filter(unicode.isdigit, s.strip())),但还是不行……

标签: python int


【解决方案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: ''

【讨论】:

  • 谢谢!我添加了一个 if 块:if(u!='')
【解决方案2】:

我建议你这样做。

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,这似乎不是一个好主意。出错总比过滤不正确好。

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 1970-01-01
    • 2021-06-25
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    相关资源
    最近更新 更多