joshua.thomas.bird
joshua.thomas.bird

Reputation: 695

How do you create a string with a single format with a variable that may hold different values in python?

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

Answers (2)

tacaswell
tacaswell

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.

new style docs

Upvotes: 1

alecxe
alecxe

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

Related Questions