Python format功能
生活随笔
收集整理的這篇文章主要介紹了
Python format功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 #通過位置2 print '{0},{1}'.format('chuhao',20)3 4 print '{},{}'.format('chuhao',20)5 6 print '{1},{0},{1}'.format('chuhao',20)7 8 #通過關鍵字參數9 print '{name},{age}'.format(age=18,name='chuhao')
10
11 class Person:
12 def __init__(self,name,age):
13 self.name = name
14 self.age = age
15
16 def __str__(self):
17 return 'This guy is {self.name},is {self.age} old'.format(self=self)
18
19 print str(Person('chuhao',18))
20
21 #通過映射 list
22 a_list = ['chuhao',20,'china']
23 print 'my name is {0[0]},from {0[2]},age is {0[1]}'.format(a_list)
24 #my name is chuhao,from china,age is 20
25
26 #通過映射 dict
27 b_dict = {'name':'chuhao','age':20,'province':'shanxi'}
28 print 'my name is {name}, age is {age},from {province}'.format(**b_dict)
29 #my name is chuhao, age is 20,from shanxi
30
31 #填充與對齊
32 print '{:>8}'.format('189')
33 # 189
34 print '{:0>8}'.format('189')
35 #00000189
36 print '{:a>8}'.format('189')
37 #aaaaa189
38
39 #精度與類型f
40 #保留兩位小數
41 print '{:.2f}'.format(321.33345)
42 #321.33
43
44 #用來做金額的千位分隔符
45 print '{:,}'.format(1234567890)
46 #1,234,567,890
47
48 #其他類型 主要就是進制了,b、d、o、x分別是二進制、十進制、八進制、十六進制。
49
50 print '{:b}'.format(18) #二進制 10010
51 print '{:d}'.format(18) #十進制 18
52 print '{:o}'.format(18) #八進制 22
53 print '{:x}'.format(18) #十六進制12
?
轉載于:https://www.cnblogs.com/alexstraze/p/9254112.html
總結
以上是生活随笔為你收集整理的Python format功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一个简单的XML文档例子
- 下一篇: 国二c语言题库 word,国家二级计算机