Q
蟒蛇,格式字符串
19
A
回答
30
"%s %%s %s" % ('foo', 'bar')
你需要%%
2
"%s %%s %s" % ('foo', 'bar') # easy!
Double%chars讓你把%的格式化爲字符串。
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}")
相關問題
- 1. 蟒蛇 - 多格式字符串%字典
- 2. 蟒蛇:字符串數組來格式化字符串
- 3. 蟒蛇:字符串
- 4. 蟒蛇字符串模式匹配
- 5. 蟒蛇從字符串
- 6. 導入字符串 - 蟒蛇
- 7. 蟒蛇:清理字符串
- 8. 地帶串字符蟒蛇
- 9. 蟒蛇:從JavaScript字符串
- 10. 蟒蛇改變字符串
- 11. 字符串到蟒蛇wstring
- 12. 字符串連接「\」蟒蛇
- 13. 獲取字符串蟒蛇
- 14. 蟒蛇:從字符串
- 15. 格式蟒蛇
- 16. 填充蟒蛇字符串日期時間按格式字符串
- 17. 蟒蛇:分割字符串的字符
- 18. 蟒蛇格式的路徑字符串列表變量
- 19. 將一個字符串(格式:01JAN2015:00:00:00)爲datetime蟒蛇
- 20. 安排列表的字符串中所需的格式蟒蛇
- 21. 未知字符串格式,蟒蛇錯誤
- 22. 蟒蛇2.7到Python 3.2字符串格式錯誤
- 23. 蟒蛇模數給字符串格式錯誤
- 24. 串聯字符串和整數蟒蛇
- 25. 蟒蛇matplotlib風格:如何使使用MATLAB樣式的格式字符串
- 26. 蟒蛇新行(字節字符串)
- 27. 蟒紋,字符串格式化
- 28. 蟒蛇從gmp字符串生成bigint
- 29. 蟒蛇如何取這些字符串
- 30. 蟒蛇評估和字符串索引
愚蠢的30個字符的限制:/ – 2011-02-08 01:00:26