python format()的用法

Python format 格式化函數符串
format()常與{}配合使用
python初學,只說簡單用法,通常format括號內一般直接填變量,字符串,常量等(用逗號分隔)。前面的{}一般格式是{<參數序號>:<格式控制標記>}
格式控制標記
1、填充:用於填充單個字符。
2、對齊:<左對齊,>右對齊,^居中對齊。
3、寬度:槽設定,輸出寬度。
4、精度:浮點數小數精度,字符串最大輸出長度。
5、類型:b,c,d,e,f,o等。

>>> print('{0} {1} {0}'.format('hello','world'))  # 打亂順序
 hello world hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world'))  # 帶關鍵字
world hello world
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+版本支持
'a, b, c'
>>> '{2}, {1}, {0}'.format(*'abc')  # 可打亂順序
'c, b, a'
>>> print('{:d}'.format(20))
20
>>> print('{:o}'.format(20))
24
>>>print('{:*^30}'.format("hhh"))
*************hhh**************
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章