Python:数字或字符串补零

版权声明:Copyright (c) 2018 strongnine https://blog.csdn.net/weixin_39679367/article/details/82226699

有时候在使用 Python 的时候,想要对一个数字或者字符串进行补零操作,即把「1」变为一个八位数的「00000001」,这个时候可以使用一下方法来进行补零。

字符串补零:

可以使用 zfill() 函数来给字符串补零:

>>> str = "123"
>>> print(str.zfill(8))
00000123

数字补零:

对于数字可以使用 格式化 的方式来进行补零:

>>> number = 123
>>> zfnumber = "%08d" % number
>>> print(zfnumber)
00000123
>>> type(zfnumber)
<class 'str'>

可以看到格式化后的数字类型变为字符类型。

猜你喜欢

转载自blog.csdn.net/weixin_39679367/article/details/82226699