【发布时间】:2011-02-08 00:58:05
【问题描述】:
我正在尝试使用惰性参数构建格式字符串,例如我需要类似:
"%s \%s %s" % ('foo', 'bar') # "foo %s bar"
我该怎么做?
【问题讨论】:
标签: python
我正在尝试使用惰性参数构建格式字符串,例如我需要类似:
"%s \%s %s" % ('foo', 'bar') # "foo %s bar"
我该怎么做?
【问题讨论】:
标签: python
"%s %%s %s" % ('foo', 'bar')
你需要 %%
【讨论】:
使用 python 2.6:
>>> '{0} %s {1}'.format('foo', 'bar')
'foo %s bar'
或使用 python 2.7:
>>> '{} %s {}'.format('foo', 'bar')
'foo %s bar'
【讨论】:
>>> "%s %%s %s" % ('foo', 'bar')
'foo %s bar'
【讨论】:
"%s %%s %s" % ('foo', 'bar') # easy!
双 % 字符可让您将 % 放入格式字符串中。
【讨论】:
%% 转义 % 符号。所以基本上你只需要写:
"%s %%s %s" % ('foo', 'bar') # "foo %s bar"
如果您需要输出百分比或其他内容:
>>> "%s %s %%%s" % ('foo', 'bar', '10')
'foo bar %10'
【讨论】:
只需使用第二个百分比符号。
In [17]: '%s %%s %s' % ('foo', 'bar')
Out[17]: 'foo %s bar'
【讨论】:
Python 3.6 现在支持使用 PEP 498 进行速记文字字符串插值。对于您的用例,新语法允许:
var1 = 'foo'
var2 = 'bar'
print(f"{var1} %s {var2}")
【讨论】:
如果你不知道参数的顺序,你可以使用字符串模板
这是一个自包含的类,它伪装成具有此功能的 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 )
【讨论】: