开发者

python, format string [duplicate]

This question already has answers here: How can I selectively escape percent (%) in Python strings? (6 answers) Closed 2 months ago.

I am trying to build a format string with lazy argument, eg I need smth like:

"%s \%s %s" % ('foo', 'bar') # "f开发者_StackOverflow社区oo %s bar"

how can i do this?


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

you need %%


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'


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


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

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


%% 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'


Just use a second percentage symbol.

In [17]: '%s %%s %s' % ('foo', 'bar')
Out[17]: 'foo %s bar'


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}")


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜