1

这让我大吃一惊。我错过了什么?

我正在尝试检测 Excel 工作表中的单元格是否为空。但似乎没有一个测试以我期望的方式工作。我希望简单的“not idkt”测试会同时检测到空字符串和无,但是没有......事实上,似乎没有 - 好吧 - 任何测试都没有检测到 None ,因为在第三行中,那就是正在打印什么。

代码:

def getFromExcelSheet():
    wb = load_workbook("input.xlsx")
    idkts = [];
    idktRows = get_worksheet_as_list(wb.get_sheet_by_name('Inputs'))
    # print "Got these idkts" 
    for row in idktRows:
        # print row[0]
        idkt = str(row[2]).strip()
        filename = str(row[3]).strip()
        if idkt == None:
            print "Idkt == none"

        if idkt is None:
            print "Idkt is none"

        if idkt == u"":
            print "Idkt is ''"

        if idkt != u"":
            print "Idkt is !=''"

        if not idkt:
            print "not IDKT"

        if idkt:
            print "idkt"

        print idkt

输出

Idkt is !=''
idkt
3398041577

Idkt is !=''
idkt
3498100937

Idkt is !=''
idkt
None
4

2 回答 2

4

idkt isn't empty, it's a string containing the word 'None'. Here's your issue:

idkt = str(row[2]).strip()

row[2] is a None, which becomes 'None' when you call str on it. Try this:

if idkt == 'None': print 'yay!'

You'd be better off testing for emptiness before the string conversion:

idkt = str(row[2]).strip() if row[2] else None
于 2012-11-20T08:44:20.053 回答
1

问题是您将单元格转换为字符串,然后将结果与 Python 的None(不是字符串)进行比较。

我假设您正在使用openpyxl在这种情况下您应该通过 访问单元格的值.value,例如

idkt = row[2].value

然后,您将拥有一个标准 Python 对象 ( str/ int/ Noneetc),它表示单元格中的数据。您应该将此值用于非空检查,它将按照您最初预期的方式运行:

if idkt not in ('', None):  # remember bool(0) == False
    ...
于 2012-11-20T08:45:29.193 回答