我正在努力使length = 001
在Python 3中,但每当我尝试打印它时,它都会截断不带前导零的值(length = 1
)。我该如何阻止这种情况发生而不需要施放length
在打印之前将其转换为字符串?
利用zfill()
用零向左填充任何字符串、整数或浮点数的辅助方法;它对两者都有效Python 2.x https://docs.python.org/2/library/string.html#string.zfill and Python 3.x https://docs.python.org/3.0/library/stdtypes.html#str.zfill.
需要注意的是,Python 2 是不再支持 https://www.python.org/doc/sunset-python-2/.
使用示例:
print(str(1).zfill(3))
# Expected output: 001
描述:
当应用于一个值时,zfill()
当初始长度达到时,返回一个用零填充的值string值小于应用的值width值,否则为初始值string值按原样。
Syntax:
str(string).zfill(width)
# Where string represents a string, an integer or a float, and
# width, the desired length to left-pad.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)