19

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 i do this?

Serenity
  • 35,289
  • 20
  • 120
  • 115
Anycorn
  • 50,217
  • 42
  • 167
  • 261

8 Answers8

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

you need %%

Foo Bah
  • 25,660
  • 5
  • 55
  • 79
17

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'
Marco Mariani
  • 13,556
  • 6
  • 39
  • 55
4
>>> "%s %%s %s" % ('foo', 'bar')
'foo %s bar'
hughdbrown
  • 47,733
  • 20
  • 85
  • 108
2
"%s %%s %s" % ('foo', 'bar') # easy!

Double % chars let you put %'s in format strings.

payne
  • 13,833
  • 5
  • 42
  • 49
2

%% 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'
Ruel
  • 15,438
  • 7
  • 38
  • 49
1

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}")
JDong
  • 2,304
  • 3
  • 24
  • 42
1

Just use a second percentage symbol.

In [17]: '%s %%s %s' % ('foo', 'bar')
Out[17]: 'foo %s bar'
Reiner Gerecke
  • 11,936
  • 1
  • 49
  • 41
0

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 )
loopbackbee
  • 21,962
  • 10
  • 62
  • 97