淺析python3字符串格式化format()函數(shù)的簡單用法
format()函數(shù)
"""
測試 format()函數(shù)
"""
def testFormat():
# format()函數(shù)中有幾個元素,前面格式化的字符串中就要有幾個 '{}'
# 位置
s1 = 'a{}b{}c{}d{}'.format(1, 2, 3, 4)
# 索引,format()函數(shù)中的元素,從0開始
s2 = 'a{0}b{1}c{3}d{2}'.format(1, 2, 3, 4)
# 索引可以重復(fù)使用
s3 = 'a{0}b{1}c{0}d{1}'.format(1, 2, 3, 4)
print('-' * 8)
print('一般用法:')
print(s1)
print(s2)
print(s3)
print('-' * 8)
# format()函數(shù)中元素個數(shù),和前面的字符串中的'{}'個數(shù)不相同
# 格式化字符串中的'{}'里面必須要有后面format()函數(shù)中元素的索引
s4 = 'a{0}b{1}cd'.format(1, 2, 3, 4)
s5 = 'a{0}b{1}c{0}d{1}e{1}f{1}g{1}h{1}{4}{4}{4}{4}{5}{4}{4}{4}{4}'.format(1, 2, 3, 4, '*', '哈哈,這是第6個數(shù),索引是5')
print('其他用法:')
print(s4)
print(s5)
print('-' * 8)
return
if __name__ == '__main__':
testFormat()
ps:下面看下python3字符串格式化(format)
用法:
它通過{}和:來代替?zhèn)鹘y(tǒng)%方式
1、使用位置參數(shù)
要點:從以下例子可以看出位置參數(shù)不受順序約束,且可以為{},只要format里有相對應(yīng)的參數(shù)值即可,參數(shù)索引從0開,傳入位置參數(shù)列表可用*列表
>>> li = ['hoho',]
>>> 'my name is {} ,age {}'.format('hoho',)
'my name is hoho ,age '
>>> 'my name is {} ,age {}'.format(,'hoho')
'my name is hoho ,age '
>>> 'my name is {} ,age {} {}'.format(,'hoho')
'my name is hoho ,age hoho'
>>> 'my name is {} ,age {}'.format(*li)
'my name is hoho ,age '
2、使用關(guān)鍵字參數(shù)
要點:關(guān)鍵字參數(shù)值要對得上,可用字典當(dāng)關(guān)鍵字參數(shù)傳入值,字典前加**即可
>>> hash = {'name':'hoho','age':}
>>> 'my name is {name},age is {age}'.format(name='hoho',age=)
'my name is hoho,age is '
>>> 'my name is {name},age is {age}'.format(**hash)
'my name is hoho,age is 18'
3、填充與格式化
:[填充字符][對齊方式 <^>][寬度]
>>> '{:*>}'.format() ##右對齊
'********'
>>> '{:*<}'.format() ##左對齊
'********'
>>> '{:*^}'.format() ##居中對齊
6 '****10****'
4、精度與進(jìn)制
>>> '{:.f}'.format(/)
'.'
>>> '{:b}'.format() #二進(jìn)制
''
>>> '{:o}'.format() #八進(jìn)制
''
>>> '{:x}'.format() #進(jìn)制
'a'
>>> '{:,}'.format() #千分位格式化
',,,'
5、使用索引
>>> li
['hoho', ]
>>> 'name is {[]} age is {[]}'.format(li)
'name is hoho age is
總結(jié)
以上所述是小編給大家介紹的python3字符串格式化format()函數(shù)的簡單用法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
python正則表達(dá)式修復(fù)網(wǎng)站文章字體不統(tǒng)一的解決方法
python正則表達(dá)式修復(fù)網(wǎng)站文章字體不統(tǒng)一的解決方法,需要的朋友可以參考一下2013-02-02
Python中實現(xiàn)字符串類型與字典類型相互轉(zhuǎn)換的方法
這篇文章主要介紹了Python中實現(xiàn)字符串類型與字典類型相互轉(zhuǎn)換的方法,非常實用,需要的朋友可以參考下2014-08-08

