格式化输出

python一共有两种格式化输出语法,

一种是类似于C语言printf的方式,称为 Formatting Expression  就是通过%来实现的

%s    字符串 (采用str()的显示)

%r    字符串 (采用repr()的显示)

%c    单个字符

%b    二进制整数

%d    十进制整数

%i    十进制整数

%o    八进制整数

%x    十六进制整数

%e    指数 (基底写为e)

%E    指数 (基底写为E)

%f    浮点数

%F    浮点数,与上相同

%g    指数(e)或浮点数 (根据显示长度)

%G    指数(E)或浮点数 (根据显示长度)

其中比较常用的有 %s, %d,%f

例:

name ="ols"
age=18
print("my name is %s ,my age is %s" %(name,age))
>>>my name is ols ,my age is 18

python的神奇之处在于它又提供了一种非常方便的语法。只需要在 typecode(这里是f)之前加一个 *,浮点数的精度就用它前面的数字来指定。
pion =3.1415926
for i in range(5):
print("The first %d bits of PI are %.*f" %(i,i,pion))
>>>

The first 0 bits of PI are 3
The first 1 bits of PI are 3.1
The first 2 bits of PI are 3.14
The first 3 bits of PI are 3.142
The first 4 bits of PI are 3.1416

从结果可以看到,竟然还会自动四舍五入

 

 

另一种是类似于C#的方式,称为String Formatting Method Calls 就是通过{}来实现的

print("my name is {_name} ,my age is {_age}" .format(_name=name,_age=age))

>>>my name is ols ,my age is 18

也可以按顺序来

print("my name is {0} ,my age is {1}" .format(name,age))

>>>my name is ols ,my age is 18

批量控制精度 

for i in range(5):
print("The first {0} bits of PI are {1:.{0}f}" .format(i,pion))
>>>

The first 0 bits of PI are 3
The first 1 bits of PI are 3.1
The first 2 bits of PI are 3.14
The first 3 bits of PI are 3.142
The first 4 bits of PI are 3.1416

 

posted @ 2017-10-20 09:24  ols888  阅读(131)  评论(0编辑  收藏  举报