format-字符串格式化

顺序写入:{}
a='{} ---- {} ----- {}'.format('abort','bank','cat')                  #abort ---- bank ----- cat
数字指定传入的参数:{2}
a='{2} ---- {0} ----- {2}'.format('abort','bank','cat')             #cat ---- abort ----- cat
指定传入的参数、长度:{2:5s}
a='{2:5s} ---- {2:5s} ----- {2:10s} ----'.format('abort','bank','cat')      #cat   ---- cat   ----- cat        ----
传入元组:(*tuple_var)
b=('abort','bank','cat','def')
a='{} ---- {} ----- {}'.format(*b)
传入元组2:(*tuple_var)
t=(111,444)
h='x:{0[0]}---y:{0[1]}'.format(t)                                        x:111---y:444
关键字参数:{key}
h='--- a={a}--- b={b}'.format(a=111,b=222,c=333)         #--- a=111--- b=222                                       x:111---y:444
传入字典:(**dict_var)
d={'a':111,'b':222,'c':333}
h='--- a={a}--- b={b}'.format(**d)                                     #--- a=111--- b=222
传入对象
c=22+33j
h='real:{0.real}----imag:{0.imag}'.format(c)                  #real:22.0----imag:33.0      
h='real:{a.real}----imag:{a.imag}'.format(a=c)              #real:22.0----imag:33.0      
左对齐,右对齐,居中
h='{:<30}'.format('left aligned')        
print(h) #'left aligned                  '
h='{:>30}'.format('right aligned')
print(h) #'                 right aligned'
h='{:^30}'.format('centered')
print(h)        #'           centered           '
h='{:*^30}'.format('centered')  # use '*' as a fill char:***********centered***********
print(h)
正数前用加号或空格填充
h='---{0:+f}----{0: f}---{0:f}---'.format(3.14, -3.14)            #---+3.140000---- 3.140000---3.140000---
其他进制:加#的区别
h="int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)                #int: 42;  hex: 2a;  oct: 52;  bin: 101010
print(h)                                
h="int: {0:#d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)        #int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010
print(h)
>>> "{:x}".format(4275878544)
'fedcba90'
>>> "{:#x}".format(4275878544)
'0xfedcba90'
>>> "{:20x}".format(4275878544)
'            fedcba90'
>>> "{:#20x}".format(4275878544)
'          0xfedcba90'
千分符:,
h='{:,}'.format(1234567890)                         #1,234,567,890
限制小数位:.
h='Correct answers: {:.3%}'.format(9/11)            #Correct answers: 81.818%
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值