1

This blows my mind. What am I missing?

I am trying to detect if a cell in an Excel sheet is empty or not. But none of the tests seem to work in the way I expect. I would expect that the simple "not idkt" test would detect both empty strings and None, but no... In fact, it seems like None is not detected by - well - any of the tests, because in the third row, that's what is getting printed.

Code:

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

Output

Idkt is !=''
idkt
3398041577

Idkt is !=''
idkt
3498100937

Idkt is !=''
idkt
None
3
  • 2
    What does it say if you print repr(idkt) on the last line? Commented Nov 20, 2012 at 8:40
  • '3398041577', '3498100937', None' Commented Nov 20, 2012 at 8:45
  • if the None has ' around it, it is a string (and not the None constant...) Commented Nov 20, 2012 at 8:48

2 Answers 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
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is that you're converting the cells to strings, and then comparing the result to the Python's None (which is not a string).

I assume you're using openpyxl in which case you should access the value of the cell via .value, e.g.

idkt = row[2].value

You will then have a standard Python object (str/int/None etc) that represents that data within the cell. You should use this value for your non-empty check, and it will behave the way you originally expected:

if idkt not in ('', None):  # remember bool(0) == False
    ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.