Python数据格式化

Python有两种格式化字符串的方式,使用%或者使用内置format()函数。

使用%格式化字符串

在Python中使用%来格式化字符串,用法和效果类似于C语言中的%。格式为:%特定的转换类型 %data。

以下是常用的转换类型

%s   字符串
%d   十进制整数
%x   十六进制整数
%o   八进制整数
%f   十进制浮点数
%e   科学计数法表示浮点数
%g   十进制或科学计数法表示的浮点数
%%   %本身

 

 

 

 

 

 

使用%格式化的例子,如下

 1 >>> n = 52
 2 >>> f = 72.08
 3 >>> s = 'this is a test string'
 4 >>> '%s %s %s' %(n,f,s)
 5 
 6 >>> print('%s\n%s\n%s' %(n,f,s))  //以%s的方式输出
 7 52
 8 72.08
 9 this is a test string
10 
11 >>> print('%d\n%d' %(n,f))    //以%d的方式输出
12 52
13 72
14 
15 字符串只能以%s的方式输出
16 
17 >>> print('%f\n%f' %(n,f))    //以%f的方式输出
18 52.000000
19 72.080000
20 
21 
22 >>> print('%10d\n%10f\n%10s' %(n,f,s))  //设置最小宽度为10,默认右对齐
23         52
24  72.080000
25 this is a test string
26 
27 >>> print('%-10d\n%-10f\n%-10s' %(n,f,s))  //左对齐
28 52        
29 72.080000 
30 this is a test string
31 
32 >>> print('%-10.4d\n%-10.4f\n%-10.4s' %(n,f,s)) //设置小数点精度
33 0052      
34 72.0800   
35 this

 

使用format()函数格式化字符串

使用内置format()函数格式化数据要和{}配合使用。以下是一些使用的例子。

 1 >>> n = 52
 2 >>> f = 72.08
 3 >>> s = 'this is a test string'
 4 >>> print('{}\n{}\n{}'.format(n,f,s))  //最简单的使用方式
 5 52
 6 72.08
 7 this is a test string
 8 
 9 >>> print('{1}\n{2}\n{0}'.format(n,f,s))  //可以通过这种方式设置输出的顺序,默认0是最开始的位置,这里表示依次输出第二个、第三个、第一个数据
10 72.08
11 this is a test string
12 52
13 
14 //format的参数可以是命名变量,或者是字典形式
15 >>> print('{f}\n{n}\n{s}'.format(n=52,f=72.08,s='this is a test string'))
16 72.08
17 52
18 this is a test string
19 
20 >>> dict1 = {'n':52, 'f':72.08, 's':'this is a test string'}
21 >>> print('{0[f]}\n{0[s]}\n{0[n]}'.format(dict1))
22 72.08
23 this is a test string
24 52
25 
26 >>> dict2 = {'n2':13, 'f2':5.08, 's2':'hello string'}
27 >>> print('{0[f]}\n{0[s]}\n{0[n]}\n{1[f2]}\n{1[n2]}\n{1[s2]}\n{2}'.format(dict1,dict2,'string3'))
28 72.08
29 this is a test string
30 52
31 5.08
32 13
33 hello string
34 string3
35 
36 //设置输出的格式
37 >>> print('{0[f]:10.4f}\n{0[s]:10.4s}\n{0[n]:10d}\n{1[f2]}\n{1[n2]}\n{1[s2]:15s}\n{2}'.format(dict1,dict2,'string3'))
38    72.0800
39 this      
40         52
41 5.08
42 13
43 hello string   
44 string3
45 
46 //可以使用>设置有对齐<设置左对齐,使用^设置居中,看下面的例子
47 >>> print('{0[f]:>10.4f}\n{0[s]:>10.4s}\n{0[n]:>10d}\n{1[f2]}\n{1[n2]}\n{1[s2]:15s}\n{2}'.format(dict1,dict2,'string3'))
48    72.0800
49       this
50         52
51 5.08
52 13
53 hello string   
54 string3
55 
56 >>> print('{0[f]:^10.4f}\n{0[s]:^10.4s}\n{0[n]:^10d}\n{1[f2]}\n{1[n2]:^10d}\n{1[s2]:15s}\n{2}'.format(dict1,dict2,'string3'))
57  72.0800  
58    this   
59     52    
60 5.08
61     13    
62 hello string   
63 string3
64 
65 //另外可以设置填充字符,填充字符的位置在:之后,在排版符(<,>,^)之前
66 >>> '{0:#^20s}'.format('center')
67 '#######center#######'

 

 

更多format()的格式化的内容点这里

 

posted @ 2016-11-02 21:38  LCdre  阅读(4632)  评论(0编辑  收藏  举报