python,格式字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4928526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:10:58  来源:igfitidea点击:

python, format string

python

提问by Anycorn

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?

我怎样才能做到这一点?

采纳答案by Foo Bah

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

you need %%

你需要 %%

回答by payne

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

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

双 % 字符可让您将 % 放入格式字符串中。

回答by Reiner Gerecke

Just use a second percentage symbol.

只需使用第二个百分比符号。

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

回答by hughdbrown

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

回答by Ruel

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

回答by Marco Mariani

with python 2.6:

使用 python 2.6:

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

or with python 2.7:

或使用 python 2.7:

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

回答by goncalopp

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 strwith this functionality (only for keyword arguments)

这是一个str具有此功能的自包含类(仅适用于关键字参数)

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 )

回答by JDong

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

Python 3.6 现在支持使用 PEP 498 的速记文字字符串插值。对于您的用例,新语法允许:

var1 = 'foo'
var2 = 'bar'
print(f"{var1} %s {var2}")