描述:Python2.6 開始,新增了一種格式化字符串的函數 str.format(),它增強了字符串格式化的功能。基本語法是通過 {} 和 : 來代替以前的 % 。使用format()來格式化字符串時,使用在字符串中使用{}作為佔位符,佔位符的內容將引用format()中的參數進行替換。可以是位置參數、命名參數或者兼而有之。
format 函數可以接受不限個參數,位置可以不按順序。
語法:format(value, format_spec)
參數:
案例:
<code># 位置參數
'{}:您{}購買的{}到了!請下樓取快遞。'.format('快遞小哥','淘寶','快遞')
'快遞小哥:您淘寶購買的快遞到了!請下樓取快遞。'
'{0}, {1} and {2}'.format('gao','fu','shuai')
'gao, fu and shuai'
x=3
y=5
'{0}+{1}={2}'.format(x,y,x+y)
# 命名參數
'{name1}, {name2} and {name3}'.format(name1='gao', name2='fu', name3='shuai')
'gao, fu and shuai'
# 混合位置參數、命名參數
'{name1}, {0} and {name3}'.format("shuai", name1='fu', name3='gao')
'fu, shuai and gao'
#for循環進行批量處理
["vec_{0}".format(i) for i in range(0,5)]
['vec_0', 'vec_1', 'vec_2', 'vec_3', 'vec_4']
['f_{}'.format(r) for r in list('abcde')]
['f_a', 'f_b', 'f_c', 'f_d', /<code>
閱讀更多 野生算法協會 的文章