1. 程式人生 > >python中format函數

python中format函數

{0} com print 表示 使用 分享圖片 bubuko alt div

python中format函數用於字符串的格式化

通過關鍵字

1 print(‘{名字}今天{動作}‘.format(名字=‘陳某某‘,動作=‘拍視頻‘))#通過關鍵字
2 grade = {‘name‘ : ‘陳某某‘, ‘fenshu‘: ‘59‘}
3 print(‘{name}電工考了{fenshu}‘.format(**grade))#通過關鍵字,可用字典當關鍵字傳入值時,在字典前加**即可

通過位置

1 print(‘{1}今天{0}‘.format(‘拍視頻‘,‘陳某某‘))#通過位置
2 print(‘{0}今天{1}‘.format(‘陳某某‘,‘拍視頻‘))

填充和對齊^<>分別表示居中、左對齊、右對齊,後面帶寬度

1 print(‘{:^14}‘.format(‘陳某某‘))
2 print(‘{:>14}‘.format(‘陳某某‘))
3 print(‘{:<14}‘.format(‘陳某某‘))
4 print(‘{:*<14}‘.format(‘陳某某‘))
5 print(‘{:&>14}‘.format(‘陳某某‘))#填充和對齊^<>分別表示居中、左對齊、右對齊,後面帶寬度
技術分享圖片
精度和類型f精度常和f一起使用
1 print(‘{:.1f}‘.format(4.234324525254))
2 print(‘{:.4f}‘.format(4.1))
進制轉化,b o d x 分別表示二、八、十、十六進制
print(‘{:b}‘.format(250))
print(‘{:o}‘.format(250))
print(‘{:d}‘.format(250))
print(‘{:x}‘.format(250))
千分位分隔符,這種情況只針對與數字
print(‘{:,}‘.format(100000000))
print(‘{:,}‘.format(235445.234235))

python中format函數