format函數(shù)使用方法

本人只是初學(xué)階段,在學(xué)習(xí)過程中的一些筆記。想借此平臺(tái)也分享給剛剛學(xué)習(xí)的朋友,如有錯(cuò)的地方歡迎各位大神與高手指點(diǎn)。

通過{} 和 :??替換 %

通過format函數(shù)可以接受不限參數(shù)個(gè)數(shù)、不限順序

format括號(hào)內(nèi)用=給變量賦值

例子一:

a =?1

b =?2

c =?3

print('{x}+{y}+{z}={w}'.format(x=a,?y=b,?z=c,?w=a + b + c))


例子二:

def?debug(func):

?def?wrapper():

?print("[DEBUG]: enter {}".format(func.__name__))

?return?func()

?return?wrapper

@debug

def?say_hello():

?print("hello!")

say_hello()

通過對(duì)象屬性

class?Person:

?def?__init__(self,?name,?age):

?self.name,?self.age = name,?age

?def?__func__(self):

?return?"This guy is {self.name}, is {self.age} old".format(self=self)

s = Person('single',?4)

a1 = s.__func__()

print(a1)

填充和對(duì)齊

^<>分別表示居中、左對(duì)齊、右對(duì)齊,后面帶寬度

print('{:>10}'.format('single'))?# 右對(duì)齊

'????single'

print('{:<10}'.format('single'))?# 左對(duì)齊

'single????'

print('{:^10}'.format('single'))?# 居中

'??single??'

精度和類型f

精度常和f一起使用

print('{:.2f}'.format(3.1415))?# 精密到2位

‘3.14'

print('{:.4f}'.format(3.1))?# 精密到4位

‘3.1000'

進(jìn)制轉(zhuǎn)化

其中b o d x分別表示二、八、十、十六進(jìn)制

print('{:b}'.format(10))?# 二進(jìn)制

‘1010'

print('{:o}'.format(10))?# 八進(jìn)制

‘12'

print('{:d}'.format(10))?# 十進(jìn)制

‘10'

print('{:x}'.format(10))?# 十六進(jìn)制

‘a(chǎn)'

千位分隔符

只針對(duì)數(shù)字

print('{:,}'.format(1000000))?# 整數(shù)

'1,000,000'

print('{:,}'.format(1000000.22555))?# 含小數(shù)

'1,000,000.22555'

print('{:,.2f}'.format(1000000.22555))?# 含小數(shù),結(jié)合精準(zhǔn)使用

'1,000,000.23'

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容