python - 如何在 Python 中用零向右填充数字字符串?

标签 python string

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/

相关文章:

python - 列出 __iadd__、+= 和返回值

c++ - 如何计算每次读入一个字符的个数?

Java 字符串在 SQL 中被错误解释

java - 如何在java(Android)中将字符串转换为条件表达式?

python - 如何在 python 和 Robot-framework 中对字典进行切片?

Python 3.4 : PyQt on Windows: Crash on exit only on some computers

python - spark - 当数据框中不存在列时设置为空

r - 尝试获取 R 中的商作为数字对象

javascript - 寻找随机选择、连接存储在变量中的文本字符串

python - M2M 字段的 Django Rest 框架嵌套序列化器的更新方法