Python中给数值型str前面加0&保留小数位(The most pythonic way to pad zeroes to string)

The most pythonic way to pad zeroes to string

Strings:

>>> n = '7'
>>> n.zfill(3)
>>> '007'

>>> '{:0>3}'.format(n)
>>> '007'
>>> '{1}{1}{0}'.format(n, '0')
>>> '007'
>>> '{:0<3}'.format(n)
>>> '700'
>>> '{:-^11}'.format(n)
>>> '-----7-----'

>>> n.rjust(3, '0')
>>> '007'
>>> n.ljust(3, '0')
>>> '700'
>>> '7'.center(11,"-")
>>> '-----7-----'


rjust/zfill 区别:

zfill:
>>> '--txt'.zfill(10)
>>> '-00000-txt'
>>> '++txt'.zfill(10)
>>> '+00000+txt'
>>> '..txt'.zfill(10)
>>> '00000..txt'
rjust:
>>> '--txt'.rjust(10, '0')
>>> '00000--txt'
>>> '++txt'.rjust(10, '0')
>>> '00000++txt'
>>> '..txt'.rjust(10, '0')
>>> '00000..txt'

numbers:

>>> n = 7
>>> print '%03d' % n
007
>>> print format(n, '03') # python >= 2.6
007
>>> print '{0:03d}'.format(n)  # python >= 2.6
007
>>> print '{foo:03d}'.format(foo=n)  # python >= 2.6
007
>>> print('{:03d}'.format(n))  # python >= 2.7 + python3
007
>>> print('{0:03d}'.format(n))  # python 3
007
>>> print(f'{n:03}') # python >= 3.6
007

% formatting 已被 string.format 替代

保留小数位:

format(value, '.6f')

>>> format(7.0, '.6f')
'7.000000'
>>> '{:.6f}'.format(7.0)
'7.000000'

作者:Chihwei_hsu
来源:http://chihweihsu.com
Github:https://github.com/HsuChihwei

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值