Rodolfo Rodolfo - 10 months ago 49
Python Question

Formatting multiple %s with a single variable

I have a string with unknown number of

that need to be formatted with a single string.

For instance, if I had the string
"%s some %s words %s"
and wanted to format it with the word
it should output
"house some house words house"

Doing the following gives me an error:

>>> "%s some %s words %s" % ("house")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

So, I decided to do the following, which works but seem to be overly complex for such a simple problem.

var = "house"
tup = (var,)
while True:
print "%s some %s words %s" % tup
tup += (var,)

Is there a more pythonic way of doing this?

Answer Source

If you know for sure you're subbing %s you can do it like this:

var = "house"
tup = (var,)
txt = "%s some %s words %s"

print txt % (tup * txt.count("%s"))

But a better solution is to use str.format() which uses a different syntax, but lets you specify items by number, so you can reuse them:

var = "house"
txt = "{0} some {0} words {0}"

print txt.format(var)