2011-02-08 111 views
19

我想建立一個格式字符串懶惰的說法,比如我需要像水木清華:蟒蛇,格式字符串

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

我怎樣才能做到這一點?

回答

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

你需要%%

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

Double%chars讓你把%的格式化爲字符串。

+1

愚蠢的30個字符的限制:/ – 2011-02-08 01:00:26

1

只需使用第二個符號。

In [17]: '%s %%s %s' % ('foo', 'bar') 
Out[17]: 'foo %s bar' 
4
>>> "%s %%s %s" % ('foo', 'bar') 
'foo %s bar' 
2

%%逃脫%符號。所以基本上你只需要編寫:

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

而且如果有的話,你需要輸出的百分比或東西:

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

與Python 2.6:

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

或使用Python 2.7:

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

如果你不「知道這個參數將被suplied的順序,你可以使用字符串模板

這裏是一個自包含的類,作爲一個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) 
0

的Python 3.6現在支持速記文字字符串插補PEP 498爲您的使用情況下,新語法允許:

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