Python format函數(shù)詳談
Python字符串的format函數(shù)
format()函數(shù)用來收集其后的位置參數(shù)和關(guān)鍵字段參數(shù),并用他們的值填充字符串中的占位符。通常格式如下:
'{pos or key : fill, align, sign, 0, width, .precision, type}'.format(para1...)
整個花括號是一個占位符,冒號前的位置或者關(guān)鍵字用來定位format函數(shù)的參數(shù),冒號后面用來將該參數(shù)格式化,其中每一個都是可選項。
1.fill用來指定填充字符,默認(rèn)為空格
2.align指定對齊方式:>為右對齊,<為左對齊,^為居中對齊
3.sign指定是否保留正負(fù)號:+為保留正負(fù)號,-為僅保留負(fù)號
4.寬度前面如果加0則表示用0填充
5.width指定寬度
6.precision指定精確度
7.type指定類型,如b為二進(jìn)制,x為十六進(jìn)制
一些示例如下:
#使用位置進(jìn)行填充
print(
'Hello,{0}. My name is {1}. How\'s it going?'.format('Hialry','Vergil')
#Hello,Hialry. My name is Vergil. How's it going?
)
#若格式中未指定填充位置,將會按序填充
print(
'{}--{}--{}--{}--{}--{}--{}'.format(1,2,3,4,5,6,7)
#1--2--3--4--5--6--7
)
#使用關(guān)鍵字段進(jìn)行填充
print(
'I\'m {name1}, and I miss u so much, {name2}.'.format(name1='vergil',name2='hilary')
#I'm vergil, and I miss u so much, hilary.
)
#使用下標(biāo)填充
names=['hilary','vergil','nero']
places=['chengdu','shijiazhuang','tokyo']
print(
'Hi, {names[0]}. I am {names[1]} and this is {names[2]}.'.format(names=names)
#Hi, hilary. I am vergil and this is nero.
)
print(
'Three people:{0[0]}, {0[1]}, {0[2]} from three places:{1[0]}, {1[1]}, {1[2]}.'.format(names,places)
#Three people:hilary, vergil, nero from three places:chengdu, shijiazhuang, tokyo.
)
#進(jìn)制轉(zhuǎn)換
print(
'{0:b}, {0:o}, {1:d}, {1:x}'.format(256,512)
#100000000, 400, 512, 200
)
#逗號分隔
print(
'{:,}'.format(12345678)
#12,345,678
)
#浮點數(shù)格式
print(
'{:+12.3f}'.format(3.14159265358979)
#+3.142
)
#對齊與填充
print(
'{:>010}'.format(12), #右對齊,寬度10,填充0
'{:0<+12.3f}'.format(-12.34567),#填充0,左對齊,保留正負(fù)號,寬度12,保留3位小數(shù)
'|{:^10}|'.format(3) #,默認(rèn)填充空格,居中對齊,寬度10
#0000000012 -12.34600000 | 3 |
)
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注本站的更多內(nèi)容!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信