Search code examples
pythonstringstring-formatting

looping over python list and string formating


loop a list in string formatted list

I have the following variables

BUILDING = "123"
SIDE = "ProductionA"
TODO = "traveling without moving"

I have the following list

OS = ["Linux", "Unix", "Windows"]

I create a formatted string list

FLIST = [
"I am installing in {}, side {} using the {} cd".format (BUILDING,SIDE,o),
"Other random stuff",
"Even more random stuff: ".format(TODO)]

I want to loop the loop the list:

for o in OS:
    print(o)
    for f in FLIST:
        print(f)

I am hoping to get:

"I am installing in 123, side ProductionA using the Linux cd"
"Other random stuff",
"Even more random stuff: traveling without moving"

"I am installing in 123, side ProductionA using the Unix cd"
"Other random stuff",
"Even more random stuff: traveling without moving"

"I am installing in 123, side ProductionA using the Windows cd"
"Other random stuff",
"Even more random stuff: traveling without moving"

The print(o) works, i am getting the values(Linux,Unix,Window) if i omit the OS in the format string.

I am installing in {}, side {} using the {} cd".format (BUILDING,SIDE)

But the o variable is not accepted by the formatted list, the error i am getting is:

NameError: name 'o' is not defined.

Help is appreciated.


Solution

  • try making a function FLIST that takes o as a parameter:

    def FLIST(o):
        return [
            "I am installing in {}, side {} using the {} cd".format (BUILDING,SIDE,o), 
            "Other random stuff",
            "Even more random stuff: ".format(TODO)
        ]
    

    then use this function:

    for o in OS:
        print(o)
        for f in FLIST(o):
            print(f)