Reputation: 695
I'm trying to do something along the lines of this:
string = "this is my %s string" % (foo)
list = ["first", "second", "g", "last"]
for entry in list:
foo = entry
print(string)
Though it seems foo needs to be declared before string, and the string is evaluated before my for loop. Is there something more Pythonic I'm missing?
Upvotes: 0
Views: 53
Reputation: 87386
fmt_str ='out {}'
for val in ["a", "b", 1]:
print fmt_str.format(val)
prints:
out a
out b
out 1
You need to do the formatting of the string inside of your loop. When you format the string (using either the old %
or new style format
) it returns the result, not a function that binds over foo
.
Upvotes: 1
Reputation: 473893
It should be:
string = "this is my %s string"
l = ["first", "second", "g", "last"]
for entry in l:
print(string % entry)
prints:
this is my first string
this is my second string
this is my g string
this is my last string
Note that calling a variable list
is a bad practice since it shadows built-in.
Upvotes: 3