python, format string

后端 未结 8 1730
野性不改
野性不改 2020-12-28 18:00

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

8条回答
  •  感情败类
    2020-12-28 18:35

    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 )
    

提交回复
热议问题