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

I can do

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

but I cannot get vars into another variable so that I can create a list of vars "on the fly" with application logic. eg

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
source share
3 answers

How about this?

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

Indeed, this is a pretty dumb way to do something. If you just want to crush all the variables together in one big line, this is probably the best idea:

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

This requires at least Python 2.4.

+6
source

use list to add / remove lines, then "" .join (your list) before printing

>>> q = []
>>> for x in range(3):
    q.append("%s")
>>> "".join(q)
'%s%s%s'
>>> print "".join(q) % ("a","b","c")
abc
+3
source
n = 0
if condition:
  increment n
  vars.append(newvar)

else:
  decrement n
  vars.pop()

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

, vars; :

"".join( map( str, vars ) )
+1

Source: https://habr.com/ru/post/1759342/


All Articles