Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create python strings with placeholders with arbitrary number of elements

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 ?

like image 890
biomed Avatar asked Dec 29 '22 08:12

biomed


1 Answers

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.

like image 186
Omnifarious Avatar answered Feb 01 '23 23:02

Omnifarious