python中format函數用于字符串的格式化
自python2.6開始,新增了一種格式化字符串的函數str.format(),此函數可以快速處理各種字符串。
語法
它通過{}和:來代替%。
請看下面的示例,基本上總結了format函數在python的中所有用法
#通過位置print '{0},{1}'.format('chuhao',20)print '{},{}'.format('chuhao',20)print '{1},{0},{1}'.format('chuhao',20)#通過關鍵字參數print '{name},{age}'.format(age=18,name='chuhao')class Person: def __init__(self,name,age): self.name = name self.age = age def __str__(self): return 'This guy is {self.name},is {self.age} old'.format(self=self)print str(Person('chuhao',18))#通過映射 lista_list = ['chuhao',20,'china']print 'my name is {0[0]},from {0[2]},age is {0[1]}'.format(a_list)#my name is chuhao,from china,age is 20#通過映射 dictb_dict = {'name':'chuhao','age':20,'province':'shanxi'}print 'my name is {name}, age is {age},from {province}'.format(**b_dict)#my name is chuhao, age is 20,from shanxi#填充與對齊print '{:>8}'.format('189')# 189print '{:0>8}'.format('189')#00000189print '{:a>8}'.format('189')#aaaaa189#精度與類型f#保留兩位小數print '{:.2f}'.format(321.33345)#321.33#用來做金額的千位分隔符print '{:,}'.format(1234567890)#1,234,567,890#其他類型 主要就是進制了,b、d、o、x分別是二進制、十進制、八進制、十六進制。print '{:b}'.format(18) #二進制 10010print '{:d}'.format(18) #十進制 18print '{:o}'.format(18) #八進制 22print '{:x}'.format(18) #十六進制12總結
以上所述是小編給大家介紹的python中強大的format函數實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林站長站網站的支持!
新聞熱點
疑難解答