Laurie
Laurie

Reputation: 1229

Concatenate variable value into non-string line of code

I have the following function:

def source_sheets(sheet_name)
    gc.open(sheet_name).sheet1.get_all_records()

How can I parameterise 'sheet1', so any number can replace 1? The fact that its not a string or not within brackets is really stumping me.

Upvotes: 1

Views: 36

Answers (2)

cody
cody

Reputation: 11157

Is this gspread? Can't you use get_worksheet as shown here?

gc.open(sheet_name).get_worksheet(0).get_all_records()

Upvotes: 1

timgeb
timgeb

Reputation: 78780

IIUC, use getattr.

def source_sheets(sheet_name, sheet_num)
    sheet = getattr(gc.open(sheet_name), 'sheet{}'.format(sheet_num))
    records = sheet.get_all_records()
    # do something with records, for example return it

or possibly

def source_sheets(sheet_name, subsheet)
    sheet = getattr(gc.open(sheet_name), subsheet)
    records = sheet.get_all_records()
    # do something with records, for example return it

if the sub-sheets can have names other than 'sheet1', 'sheet2', ... and so on.

Upvotes: 1

Related Questions