python 字符串补 0
作者:解琛
时间:2020 年 8 月 14 日
一、ljust
原字符串左侧对齐, 右侧补零。
格式:
str.ljust(width, '0')
案例
>>> "123".ljust(16, "0")
'1230000000000000'
二、rjust
原字符串右侧对齐, 左侧补零。
格式:
str.rjust(width, '0')
案例
>>> "123".rjust(16, "0")
'0000000000000123'
三、zfill
左侧补零。
格式:
str.zfill(width)
案例
>>> "123".zfill(16)
'0000000000000123'
四、%
左侧补零。
案例
>>> '%016d' % 123
'0000000000000123'
本文详细介绍了使用Python进行字符串补0的四种方法:ljust、rjust、zfill及%格式化。通过具体案例展示了如何将字符串左侧或右侧对齐,并在另一侧补充0以达到固定长度。
4944

被折叠的 条评论
为什么被折叠?



