Python字符串有一个名为zfill
的方法,它可以在左侧用零填充数字字符串。
In : str(190).zfill(8)
Out: '00000190'
我该如何让这个填充物在右侧呢?
作为一种更轻便[1]且更高效[2]的替代方案,实际上您只需使用str.ljust即可。
In [2]: '190'.ljust(8, '0')
Out[2]: '19000000'
In [3]: str.ljust?
Docstring:
S.ljust(width[, fillchar]) -> str
Return S left-justified in a Unicode string of length width. Padding is
done using the specified fill character (default is a space).
Type: method_descriptor
[1] format 没有在旧版 Python 中出现。自 Python 3.0 起添加了格式说明符(参见 PEP 3101)和 Python 2.6。
[2] 反转两次是一项昂贵的操作。
"{:<08s}"
。 - Skippy le Grand Gourouf'{3:>02d}'
生成03,f'{3:<02d}'
生成30。 - Roland提示:该字符串可以反转两次:在使用zfill
方法之前和之后:
In : acc = '991000'
In : acc[::-1].zfill(9)[::-1]
Out: '991000000'
甚至更加容易的是:
In : acc.ljust(9, '0')
Out: '991000000'