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] 格式在旧的 python 版本中不存在。自 Python 3.0(参见 PEP 3101)和 Python 2.6 以来添加了格式说明符。
[2] 反转两次是一个昂贵的操作。
关于python - 如何在 Python 中用零向右填充数字字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40999973/