Python Forum

Full Version: Loop through a list of string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I would like to write the following code,

caeXmlObjects.kernel.mainXML.saveXMLRecords(fileName='settings.xml', 
    className='caeXmlObjects.paths.pathXML.PathXML', silentMode=False, outputType='File', 
    recordNames=('Path-0', 'Path-1', 'Path-2', ), params=('Path-0', 'Path-1', 'Path-2',  ), paramsPerSave=1)
but by introducing a list of paths variable, so I can have # params=('Path-0', 'Path-1', 'Path-2',...,Path-n, )
It will start like this for exemple:
Number_Fea = 3
Var_Paths = ["'Path-%d'" %i for i in range(Number_Fea)]
Perhaps something like:

number_features = 3
var_paths = [f"Path-{i}" for i in range(number_features)]
Thank you for your answer, but I'm more trying to create something like this
params=('Path-0', 'Path-1', 'Path-2',...,Path-n, )
so when I have 3 or 4 or 5 ... paths. my params=('Path-0',...) will change accordingly
Put it in a function? I'm not sure what sort of interface you're looking for.

def path_params(n):
    number_features = n
    return [f"Path-{i}" for i in range(number_features)]


params = path_params(3)
To change the number of paths in var_paths, change the value of "number_features".
import random
number_paths = random.randint(1, 10)
var_paths = [f"Path-{i}" for i in range(number_paths )]
print(var_paths)