2016-11-18 44 views
2

有沒有什麼辦法只能在字符串格式中只替換第一個參數?像這樣的:在字符串格式中,我可以一次只替換一個參數嗎?

"My quest is {test}{}".format(test="test") 

我所要的輸出是:

"My quest is test {} 

第二{} ARG我會在後面進行更換。

我知道我可以創建這樣一個字符串:

"My quest is {test}".format(test="test") 

後來用剩下的字符串結合起來,創造新的字符串,但我能做到一氣呵成?

+0

你能舉出更清晰的例子來證明你想要什麼嗎?你的問題不清楚。 –

回答

3

如果你知道,當你設置的格式字符串,您只需要替換值的子集,並且要馬上用括號加倍其他一些將繼續保持,就可以逃脫你不打算填補的:

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" 
1

如果將"{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

1

您將不得不編寫自己的格式化功能,只能進行一次替換。例如,爲了給你的東西下手(注意,這是比較容易受到不良格式字符串):

import re 
def formatOne(s, arg): 
    return re.sub('\{.*?\}', arg, s, count=1) 

像這樣來使用:

>>> s = "My quest is {test}{}" 
>>> formatOne(s, 'test') 
'My quest is test{}' 
>>> formatOne(_, ' later') 
'My quest is test later' 
0

的COR矩形的方式來實現這一目標很可能是子類string.Formatter類,並使用的,而不是字符串的方法它的實例:

from string import Formatter 
class IncrementalFormatter(Formatter): 
    pass # your implementation 
f = IncrementalFormatter() 
f.format("hello {name}", name="Tom") 

以下Formatter方法必須被覆蓋:

  1. get_value()應該返回一些特殊而不是提高LookupError
  2. get_field()應將field_name參數保存到此對象中(或者如果對象不是我們的特殊對象,則可以正常進行)。
  3. convert_field()應該只是將conversion參數保存到此對象中並且不進行任何轉換(或正常進行...)。
  4. format_field()應該使用此方法的參數field_nameconversion屬性和format_spec參數(或正常執行...)從特殊對象重建字段格式字符串。

因此,舉例來說:

f.format("{greet} {who.name!r:^16s}", greet="hello") 

應導致"hello {who.name!r:^16s}",其中"who.name"field_name"r"conversion"^16s"format_spec,所有這三個值重新組合回"{who.name!r:^16s}",使它可以在下一個格式化過程中使用。

附加說明:特殊對象在訪問任何屬性(使用.)或項目(使用[])時應返回自身。

相關問題