python--格式化输出

 

字符格式化%


 

1. 打印字符串

print ("His name is %s"%("Aviad"))

结果 His name is Aviad 

2.打印整数

print('he is %d years old'%25)

结果 he is 25 years old 

3.打印浮点数

print('he is height %f'%181.1)

结果 he is height 181.100000 

4.打印浮点数(指定保留小数点位数)

print('he is height %.2f'%181.1)

结果 he is height 181.10 

在占位符中用%.2表示要表示保留的位数

5.指定占位符宽度

print ("Name:%10s Age:%8d Height:%8.2f"%("Aviad",25,1.83))

结果 Name: Aviad Age: 25 Height: 1.83 

在占位符中用%+整数表示要表示保留总占位符宽度

6.指定占位符宽度(左对齐)

print ("Name:%-10s Age:%-8d Height:%-8.2f"%("Aviad",25,1.83))

结果 Name:Aviad Age:25 Height:1.83  

7.指定占位符(只能用0当占位符?)

print ("Name:%-10s Age:%08d Height:%08.2f"%("Aviad",25,1.83))

结果

1 Name:Aviad      Age:00000025 Height:00001.83
 8.输出%符号
>>>print("超过 %d%%用户"%12.00)
超过 12%用户
如要在占位符中输出%符号用%转译
更多类型占位符使用

 

 
 

字符格式化format


 

举例: 

>>> print("{:.4}".format(3.1415926)) 
3.142

format中有丰富的格式限定符,有很多格式限定的方法:

1、填充与对齐

填充常跟对齐一起使用 
^、<、>分别是居中、左对齐、右对齐,后面带宽度 
:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充 
比如

>>> print("{:>7}".format(12))
     12
>>> print("{:0>7}".format(12))
0000012
>>> print("{:a>7}".format(12))
aaaaa12

2、精度与类型

举例:

print("{:.2f}".format(12))
12.00

下表展示了 str.format() 格式化数字的多种方法:

数字格式输出描述
3.1415926 {:.2f} 3.14 保留小数点后两位
3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
-1 {:+.2f} -1.00 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指数记法


 

posted @ 2018-03-30 18:03  Ronny_bin  阅读(51)  评论(0)    收藏  举报