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

你可能感兴趣的:(Python,Pythonic)