字符串格式化

 1 #coding=utf-8
 2 '''
 3 字符串格式化
 4 '''
 5 
 6 #~~~~~~替换元素作用
 7 #默认顺序替换
 8 print('hello,{},{},{}'.format('z','c','zc'))
 9 
10 #使用关键字进行对应变量的替换
11 print('hello,{y},{x},{z}'.format(x='z',y='c',z='zc'))
12 
13 #使用索引序号进行替换
14 print('hello,{1},{0},{2}'.format('z','c','zc'))
15 print('hello,{1[1]},{0},{2}'.format('z',('c','cc','ccc'),'zc'))
16 print('hello,{1[1]},{0[1]},{2}'.format(('z','zz','zzz'),('c','cc','ccc'),'zc'))
17 
18 #使用关键字和索引序号进行对应变量的替换
19 print('hello,{1[1]},{0[1]},{x}'.format(('z','zz','zzz'),('c','cc','ccc'),x='zc'))
20 
21 
22 #~~~~~~规范格式
23 #指定精度
24 print('此次的小数是:{:.5f}'.format(3.1415926))
25 print('此次的小数是:{:.2f}'.format(3.1415926))
26 
27 #指定进制
28 print('13的二进制是:{:b}'.format(13))
29 print('13的八进制是:{:o}'.format(13))
30 print('13的十进制是:{:d}'.format(13))
31 print('13的十六进制是:{:x}'.format(13))
32 
33 #对齐方式
34 #print('x表示填充的样式,>表示右对齐,y表示要展示的宽度{:x>y}'.format(13))
35 print('x表示填充的样式,>表示右对齐,y表示要展示的宽度{:x>10}'.format(13))
36 print('x表示填充的样式,<表示左对齐,y表示要展示的宽度{:x<10}'.format(13))
37 print('x表示填充的样式,^表示居中对齐,y表示要展示的宽度{:x^10}'.format(13))

 

posted on 2018-08-13 11:12  DAY&DAY&UP  阅读(90)  评论(0)    收藏  举报

导航