'How do you change parts of a string with a list variable in a for loop?

I want to open many files to do an analysis through python. The title changes in three ways, ID, intervention and drug_type

So I define the path where the files are and create three list variables which contain the names I want to swap parts of the string with.

path = r'R:\Storage\healthsciences\SPRH\pwelch' 

ID = ['P1','P2','P3','P4','P5'] 
intervention = ['intervention1','intervention2'] 
drug_type = ['drug1','drug2','drug3','drug4']

filename = P1_intervention1_drug2_pwelch_output

How would I get the different sections to change in a for loop?

So..

filename = 

[ID]'_'[intervention]'_'drug_type'_pwelch_output.mat'

with each list variable changing as it loops over

Any push in the right direction is much appreciated :)



Solution 1:[1]

ids = ['P1','P2','P3','P4','P5']
interventions = ['intervention1', 'intervention2']
drug_types = ['drug1','drug2','drug3','drug4']

for id in ids:
    for intervention in interventions:
        for drug_type in drug_types:
            filename = f"{id}_{intervention}_{drug_type}_pwelch_output.mat"
            # use the filename

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kenny