python, format string

后端 未结 8 1681
野性不改
野性不改 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:25

    with python 2.6:

    >>> '{0} %s {1}'.format('foo', 'bar')
    'foo %s bar'
    

    or with python 2.7:

    >>> '{} %s {}'.format('foo', 'bar')
    'foo %s bar'
    
    0 讨论(0)
  • 2020-12-28 18:26

    Python 3.6 now supports shorthand literal string interpolation with PEP 498. For your use case, the new syntax allows:

    var1 = 'foo'
    var2 = 'bar'
    print(f"{var1} %s {var2}")
    
    0 讨论(0)
  • 2020-12-28 18:31

    %% escapes the % symbol. So basically you just have to write:

    "%s %%s %s" % ('foo', 'bar') # "foo %s bar"
    

    And if ever you need to output a percentage or something:

    >>> "%s %s %%%s" % ('foo', 'bar', '10')
    'foo bar %10'
    
    0 讨论(0)
  • 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 )
    
    0 讨论(0)
  • 2020-12-28 18:37

    Just use a second percentage symbol.

    In [17]: '%s %%s %s' % ('foo', 'bar')
    Out[17]: 'foo %s bar'
    
    0 讨论(0)
  • 2020-12-28 18:38
    "%s %%s %s" % ('foo', 'bar')
    

    you need %%

    0 讨论(0)
提交回复
热议问题