1 格式化输出
在之前的课程中,有顺带的提过格式化输出,如下按照某某某's weight is … and height is …
格式进行输出
name = 'Hades'
weight = 125
height = 168
print(name + "'s weight is " + str(weight) + ' and height is ' + str(height))
Hades's weight is 125 and height is 168
这看起来还是可以的,但是在打印的时候一不小心就会报错,因为weight和height都是数字,不能与字符串进行相加,所以还需要进行数据类型转换,将int转换成str,这样就多了很多会出错的操作,很不方便。
这就体现出如下三种格式化输出的优势了。
1.1 占位符(%s)
使用%s来先进行占位置,然后在进行补全,具体格式为print("%s's weight is %s and height is %s"%(name,weight,height))
name = 'Hades'
weight = 125
height = 168
print("%s's weight is %s and height is %s"%(name,weight,height))
Hades's weight is 125 and height is 168
注意:有几个占位符就必须传几个数值,不然会报错,如下:
- 占位符多了,报错
name = 'Hades'
weight = 125
height = 168
print("%s's weight is %s and height is %s %s"%(name,weight,height))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-11-4195a55b7081> in <module>
3 height = 168
4
----> 5 print("%s's weight is %s and height is %s %s"%(name,weight,height))
TypeError: not enough arguments for format string
- 传递的数据多了,报错
name = 'Hades'
weight = 125
height = 168
print("%s's weight is %s and height is %s"%(name,weight,height,height))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-6bfa2e1aafe5> in <module>
3 height = 168
4
----> 5 print("%s's weight is %s and height is %s"%(name,weight,height,height))
TypeError: not all arguments converted during string formatting
1.2 format 格式化
format格式化也是一种格式化输出,具体格式为('{} gfysr{} +1234567 {}'.format(a,b c))
相较于占位符和f-string这两种,format比较繁琐,代码量比较大,不信我们接下来看:
name = 'Hades'
weight = 125
height = 168
print("{}'s weight is {} and height is {}".format(name,weight,height))
Hades's weight is 125 and height is 168
pai = 3.1415926
print('{:.0f}'.format(pai)) # 格式化输出小数点后几位数,不够的用0添加
print('{:.4f}'.format(pai))
print('{:.10f}'.format(pai))
3
3.1416
3.1415926000
1.3 f-string格式化
f-string格式化输出比较方便,使用起来也很简单,具体格式为f"{name}'s weight is {weight} and height is {height}"
name = 'Hades'
weight = 125
height = 168
print(f"{name}'s weight is {weight} and height is {height}")
Hades's weight is 125 and height is 168
name = 'Hades'
weight = 125
height = 168
print(F'{name}’s weight is {weight} and height is {height}') # f/F都可以,''/""也是一样的
Hades’s weight is 125 and height is 168
pai = 3.1415926
print(f'{pai:.2f}') # 同样的,f-string也可以格式化输出小数点后几位数,不够的用0添加
print(f'{pai:.5f}')
print(f'{pai:.15f}')
3.14
3.14159
3.141592600000000