python 格式化输出format, f,% 小结


python格式化输出的几种方式

方法一:format

name = 'Harry'
age = 13.52
'{} is {:.0f}'.format(name, age)
>>>'Harry is 14'

方法二:f
这个是format形式的方便版

name = 'Harry'
age = 13.52
f'{name} is {age:.0f}'
>>>'Harry is 14'

方法三:%

name = 'Harry'
age = 13.52
'%s is %d' % (name, age)
>>>'Harry is 13'

下面是关于format的更多细节。

几种映射方式

位置

name = 'Tom'
age = 13
color = 'green'
'{0} is {1}. {0} likes {2} most.'.format(name, age, color)
>>> 'Tom is 13. Tom likes green most.'

关键字参数

name = 'Tom'
age = 13
color = 'green'
'{name} is {age}. {name} likes {color} most.'.format(name=name, age=age, color=color)
>>> 'Tom is 13. Tom likes green most.'

'{name} is {age}. {name} likes {color} most.'.format(name='Harry', age=20, color='blue')
>>> 'Harry is 20. Harry likes blue most.'
关键字参数和对象属性
class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age
pp = Person('Tome', 13)
'{person.name} is {person.age}'.format(person = pp)
>>> 'Tome is 13'
关键字参数和下标
pp = ['Tome', 13]
'{person[0]} is {person[1]}'.format(person = pp)
>>> 'Tome is 13'

格式

对齐和填充

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

a = 'a'
'{:>8}'.format(a)
>>> '       a'

a = 'a'
'{:0>8}'.format(a)
>>> '0000000a'

精度和类型

这个是大家最常用的,就不再赘述。

'{:.2f}'.format(100.555)
>>> '100.56'

这里可以对比一下字符串和数字在填充和精度上的区别:

'{0:4}'.format(str(5))
>>> '5   '
'{0:4}'.format(5)
>>> '   5'

参考博文
https://blog.csdn.net/fengzhizi76506/article/details/57492295

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值