How to find first non-blank string variable during string assignment?

I have Python 3.12 on Windows 10.

I work with spreadsheets. I read each row one at a time, and grab one piece of data from that row, let’s say a job number, which could be in column A, B or C. Yes, the spreadsheet is a mess, I can’t change that. I have to work with what I’m given.

But the preferred order I look for the job number in the columns is B, A, C. I need to look for a job in column B. If that’s blank, go to column A. If that’s blank use column C. Currently this requires a bunch of lines to do.

Is there a quicker way to do this?

In perl it was something like (I can’t remember the exact syntax).

# Variable row contains all columns of data for one row.
cola = row[0];
colb = row[1];
colc = row[2];
job = colb | cola | colc;

In Python I’m currently doing:

if colb: 
    job = colb
elsif cola: 
    job = cola
elsif colc:
    job = colc

Thank you!

job = next(filter(None, (colb, cola, colc)))

This will raise StopIteration if all of cola, colb, colc are empty.

What you did in Perl also works in Python, with slightly different syntax:

job = colb or cola or colc

This will set job to '' if all of cola, colb, and colc are empty.

2 Likes

Perfect! Thank you! I made a note of this.