Python自带格式化函数format()

多数情况下,格式化输出采用‘%’形式。

name=input('input your name:')
print('My name is %s'%name)

format()的功能则更为强大,通过传入的参数进行格式化,并用‘{}’作为特殊字符替代‘%’。使用方法有两种:b.format(a)和format(a,b),a为需要进行格式化的内容,b为格式。
用法一: 空白{}

print('{} {}'.format('hello', 'world'))

输出:
hello world

用法二:通过位置匹配参数

print('{1} {0}'.format('hello', 'world'))#可打乱顺序

输出:
world hello

print('{1} {0} {1}'.format('hello', 'world'))#可重复

输出:
world hello world

用法三:通过名字匹配参数

print('{b} {a} {a}'.format(a='hello', b='world'))

输出:
world hello hello

pop={'sh':45,'bj':40}
print('{sh} {bj}'.format(**pop))

输出:
45 40

用法四:通过属性匹配参数

c = 3-5j
print('The complex number {0} is formed from {0.real} and {0.imag}j'.format(c))

输出:
The complex number (3-5j) is formed from 3.0 and -5.0j

用法五:通过下标或者key值匹配参数

names=('sh','bj','sz')
print('{0[0]},{0[1]}'.format(names))

输出:
sh,bj

pop={'sh':45,'bj':40}
print('{0[sh]} {0[bj]}'.format(pop))

输出:
45 40

用法六:多种格式化
1、二进制

print('{:b}'.format(3))#二进制,等价于print(format(3,'b'))

输出:
11
2、八进制

print('{:o}'.format(3))#八进制,等价于print(format(3,'o'))

输出:
3
3、十六进制

print('{:x}'.format(3))#十六进制,等价于print(format(3,'x'))

输出:
3
4、十进制

print('{:d}'.format(12))#十进制,等价于print(format(12,'d'))

输出:
12
5、百分数

print('{:.2%}'.format(0.222))#将值乘以100,以百分数形式打印,小数点后保留两位,等价于print(format(0.222,'.2%'))

输出:
22.20%
6、浮点数

print('{:.2f}'.format(0.222))#以浮点数形式输出,精确至小数点后两位,等价于print(format(0.222,'.2f'))

输出:
0.22
用法七:对齐及设置长度
1、左对齐

'{:<30}'.format('left aligned')#等价于'{:30}'.format('left aligned')默认左对齐,也等价于format('left aligned','<30')

2、右对齐

'{:>30}'.format('left aligned')#等价于format('left aligned','>30')

3、中间对齐

'{:^30}'.format('left aligned')#等价于format('left aligned','^30')

4、填充

'{:*^30}'.format('left aligned')#*号填充,等价于format('left aligned','*^30')

输出:
left aligned

用法八:千位分隔符

'{:,}'.format(10000000000)#等价于format(10000000000,',')

输出:
‘10,000,000,000’

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值