Reputation: 43
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.
Upvotes: 3
Views: 1123
Reputation: 45741
FLIST
should rather be function taking o
as an input:
BUILDING = "123"
SIDE = "ProductionA"
TODO = "traveling without moving"
# Note f-strings only work in python 3.6+, revert to .format() if you need to use an older version
def make_flist(operating_system):
return [
f"I am installing in {BUILDING}, side {SIDE} using the {operating_system} cd",
"Other random stuff",
f"Even more random stuff: {TODO}"
]
operating_systems = ["Linux", "Unix", "Windows"]
for operating_system in operating_systems:
print(operating_system)
for statement in make_flist(operating_system):
print(statement)
Upvotes: 3
Reputation: 1181
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)
Upvotes: 2
Reputation: 3618
I have placed the FLIST
inside the loop. Try,
BUILDING = "123"
SIDE = "ProductionA"
TODO = "traveling without moving"
OS = ["Linux", "Unix", "Windows"]
for o in OS:
print(o)
FLIST = ["I am installing in {}, side {} using the {} cd".format (BUILDING,SIDE,o),"Other random stuff","Even more random stuff: {}".format(TODO)]
for f in FLIST:
print(f)
Output:
Linux
I am installing in 123, side ProductionA using the Linux cd
Other random stuff
Even more random stuff: traveling without moving
Unix
I am installing in 123, side ProductionA using the Unix cd
Other random stuff
Even more random stuff: traveling without moving
Windows
I am installing in 123, side ProductionA using the Windows cd
Other random stuff
Even more random stuff: traveling without moving
See it in action here
Upvotes: 4