I am trying to build a format string with lazy argument, eg I need smth like:
\"%s \\%s %s\" % (\'foo\', \'bar\') # \"foo %s bar\"
how can
If you don't know the order the arguments will be suplied, you can use string templates
Here's a self contained class that poses as a str
with this functionality (only for keyword arguments)
class StringTemplate(str):
def __init__(self, template):
self.templatestr = template
def format(self, *args, **kws):
from string import Template
#check replaced strings are in template, remove if undesired
for k in kws:
if not "{"+k+"}" in self:
raise Exception("Substituted expression '{k}' is not on template string '{s}'".format(k=k, s=self))
template= Template(self.replace("{", "${")) #string.Template needs variables delimited differently than str.format
replaced_template= template.safe_substitute(*args, **kws)
replaced_template_str= replaced_template.replace("${", "{")
return StringTemplate( replaced_template_str )