如何在Python中用零填充数字字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40999973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:20:25  来源:igfitidea点击:

How to pad a numeric string with zeros to the right in Python?

pythonstring

提问by yucer

Python strings have a method called zfillthat allows to pad a numeric string with zeros to the left.

Python 字符串有一个方法zfill,它允许在数字字符串的左边填充零。

In : str(190).zfill(8)
Out: '00000190'

How can I make the pad to be on the right ?

我怎样才能让垫子在右边?

回答by NarūnasK

See Format Specification Mini-Language:

请参阅格式规范迷你语言

In [1]: '{:<08d}'.format(190)
Out[1]: '19000000'

In [2]: '{:>08d}'.format(190)
Out[2]: '00000190'

回答by Manoel Vilela

As maybe a alternative more portable [1] and efficient [2], actually you can just use str.ljust.

作为更便携 [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 is not present on old python versions. format specifier was added since Python 3.0 (see PEP 3101) and Python 2.6.

[1] 格式在旧的 python 版本中不存在。自 Python 3.0(参见PEP 3101)和 Python 2.6起添加了格式说明符。

[2] reverse twice is an expensive operation.

[2] 反转两次是一项昂贵的操作。

回答by yucer

Hint: The string can be inverted twice: before and after using the zfillmethod:

提示:字符串可以反转两次:使用zfill方法之前和之后:

In : acc = '991000'

In : acc[::-1].zfill(9)[::-1]
Out: '991000000'

Or even more easier:

或者更简单:

In : acc.ljust(9, '0')
Out: '991000000'