格式化输出

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

注意:有几个占位符就必须传几个数值,不然会报错,如下:

  1. 占位符多了,报错
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
  1. 传递的数据多了,报错
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

转载于:https://www.cnblogs.com/Hades123/p/10813517.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值