views:

70

answers:

3

I can do

string="%s"*3
print string %(var1,var2,var3)

but I can't get the vars into another variable so that I can create a list of vars on the fly with app logic. for example

if condition:
  add a new %s to string variable
  vars.append(newvar)

else:
  remove one %s from string
  vars.pop()
print string with placeholders

Any ideas on how to do this with python 2.6 ?

+3  A: 

How about this?

print ("%s" * len(vars)) % tuple(vars)

Really though, that's a rather silly way to do things. If you just want to squish all the variables together in one big string, this is likely a better idea:

print ''.join(str(x) for x in vars)

That does require at least Python 2.4 to work.

Omnifarious
Works fine in 2.4, I just tried it. Why shouldn't it work?
katrielalex
+1  A: 
n = 0
if condition:
  increment n
  vars.append(newvar)

else:
  decrement n
  vars.pop()

string = "%s" * n
print string with placeholders

But you don't really need string formatting if you're just joining the vars; why not do:

"".join( map( str, vars ) )
katrielalex
+2  A: 

use a list to append/remove strings then "".join(yourlist) before printing

>>> q = []
>>> for x in range(3):
    q.append("%s")
>>> "".join(q)
'%s%s%s'
>>> print "".join(q) % ("a","b","c")
abc
pycruft
Ugh. Don't do this.
katrielalex
absolutely agree - don't do this! BUT, if for some reason you REALLY want to be able to _remove_ formatting from your string (urgh!) then this seems the simplest way. MUCH better to avoid that if possible.
pycruft