安利三个关于Python字符串格式化的进阶知识

  关于Python字符串格式化知识,相信大家也都不陌生,基础的格式化替换在此就不再赘述了,今天给大家分享的是三个字符串格式化的进阶知识,希望对大家的学习有所帮助。

1. 格式化字符"%03d"

  正常情况下我们输出一个十进制整数的时候,直接使用%d就可以满足。

number1 = 26
print("This number1 is %d." % number1)
number2 = 888
print("This number2 is %d." % number2)

运行结果:This number1 is 26.
     This number2 is 888.

  这种正常打印数字肯定没有问题,但是在生活中,如果需要打印工号、学号等等有00开头的数字,如果再使用这种格式化字符串打印的话,肯定就难以实现。

  为了实现这种格式化字符串的打印,这里引入“%03d”,其中数字3可以更改为其他数字。该字符串格式化代表的意思是控制台输出几位数字,如果数字是3,就输出3个数字,如果实际的数字大于3位数的话,就输出原始数据,如果小于3位数的话,则在前面自动补0。

number1 = 26
print("This number1 is %03d" % number1)
print("This number1 is %06d" % number1)

number2 = 888
print("This number2 is %03d" % number2)
print("This number2 is %06d" % number2)

number3 = 888888
print("This number3 is %03d" % number3)
print("This number3 is %06d" % number3)

运行结果:This number1 is 026.
     This number1 is 000026.
     This number2 is 888.
     This number2 is 000888.
     This number3 is 888888.
     This number3 is 888888.

  通过以上方法就可以顺利的打印学号、工号等以0开始的字符串,而且显得特别的对齐工整。

2. 格式化字符"%.2f"

  在Python中格式化打印浮点数的时候,一般会默认打印小数点后6位。

weight = 64.5
print("His weight is %f kg." % weight)

运行结果:His weight is 64.500000 kg.

  但是实际上我们并不需要那么多的小数位,一般我们习惯性保留两位小数位,那么我们可以使用格式符"%.2f"的形式,其中数字2表示保留两位小数,如果你需要保留3位小数的话,那么你就可以将2变成3即可。

weight = 64.5
print("His weight is %.2f kg." % weight)

print("His weight is %.3f kg." % weight)

运行结果:His weight is 64.50 kg.
     His weight is 64.500 kg.

3. 格式化字符"%s"

  在Python格式化字符串里边,有一个格式化符号非常的给力,那就是"%s",为啥这么说呢?因为它不仅可以格式化输出打印字符串,还可以格式化输出数字、浮点数。

age = 26
weight = 64.5
id = 2
print("His age is %s, weight is %.2f kg, id is %d." % (age, weight, id))
print("His age is %s, weight is %s kg, id is %s." % (age, weight, id))

运行结果:His age is 26, weight is 64.50 kg, id is 2.
     His age is 26, weight is 64.5 kg, id is 2.

   从上面例子中可以看到,使用格式化符号%d,%f 可以打印出结果,使用%s也可以打印出来,这个就比较特殊了。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值