Python 在字符串格式中,一次只能替换一个参数吗?
有没有办法只替换字符串格式中的第一个参数?就像这样:Python 在字符串格式中,一次只能替换一个参数吗?,python,python-3.x,string-formatting,Python,Python 3.x,String Formatting,有没有办法只替换字符串格式中的第一个参数?就像这样: "My quest is {test}{}".format(test="test") 我希望输出为: "My quest is test {} 第二个{}arg I稍后将替换 我知道我可以创建如下字符串: "My quest is {test}".format(test="test") 然后将其与剩余字符串组合并创建新字符串,但我可以一次性完成吗?在同一行中替换它的唯一方法是使用另一个括号替换“{test}”。即: s = "My qu
"My quest is {test}{}".format(test="test")
我希望输出为:
"My quest is test {}
第二个{}
arg I稍后将替换
我知道我可以创建如下字符串:
"My quest is {test}".format(test="test")
然后将其与剩余字符串组合并创建新字符串,但我可以一次性完成吗?在同一行中替换它的唯一方法是使用另一个括号替换
“{test}”
。即:
s = "My quest is {test}".format(test="test {}").format('testing')
但这没有多大意义,因为你本可以做到:
s = "My quest is {test} {}".format('testing', test="test {}")
马上
您可以保留以下结果:
s = "My quest is {test}".format(test="test {}")
因此,
s
中有一个括号,等待替换,如果需要,可以稍后调用format
您必须编写自己的格式函数,只进行一次替换。例如,为您提供一些开始的内容(请注意,这在某种程度上容易受到格式错误字符串的影响):
这样使用:
>>> s = "My quest is {test}{}"
>>> formatOne(s, 'test')
'My quest is test{}'
>>> formatOne(_, ' later')
'My quest is test later'
如果您知道在设置格式字符串时,您将只替换值的一个子集,并且希望保留另一个值集,则可以通过将括号加倍来避开不打算立即填充的值:
x = "foo {test} bar {{other}}".format(test="test") # other won't be filled in here
print(x) # prints "foo test bar {other}"
print(x.format(other="whatever")) # prints "foo test bar whatever"
实现这一点的正确方法可能是对类进行子类化,并使用其实例而不是string方法:
from string import Formatter
class IncrementalFormatter(Formatter):
pass # your implementation
f = IncrementalFormatter()
f.format("hello {name}", name="Tom")
必须覆盖以下格式化程序方法:
get\u value()
应该返回一些特殊对象,而不是引发LookupError
get\u field()
应将field\u name
参数保存到此对象中(如果该对象不是我们的特殊对象,则正常进行)
convert\u field()
format\u field()
应使用此方法的field\u name
和conversion
属性和format\u spec
参数从特殊对象重构字段格式字符串(或正常进行…)
例如:
f.format("{greet} {who.name!r:^16s}", greet="hello")
应该导致“hello{who.name!r:^16s}”
,其中“who.name”
是字段名
,“r”
是转换
,“^16s”
是格式规范
,所有这三个值都重新组合回“{who.name!r:^16s}”
,以便在下一次格式化过程中使用
附加说明:在访问任何属性(使用
)或项目(使用[]
)时,特殊对象应返回自身。您能给出更清楚的示例来说明您想要什么吗?你的问题不清楚。如果我需要格式化,比如说4次,我需要将一些占位符包装成4对括号,如:my_str=“{first},{{second},{{{third}},{{{{third}},{{{third}}},{{{third}}},{code>,不,每次都需要加倍:{code>{first},{{second second},{{{third},{{{third},{{{second。如果确实需要这样做,您可能需要使用其他方法之一(如second=“{second}”
)。
f.format("{greet} {who.name!r:^16s}", greet="hello")