问题描述
我正在尝试在Python 3中制作length = 001
,但是每当我尝试将其打印出来时,它都会截断没有前导零(length = 1
)的值.我如何停止这种情况而不必在打印出来之前将length
强制转换为字符串?
I'm trying to make length = 001
in Python 3 but whenever I try to print it out it truncates the value without the leading zeros (length = 1
). How would I stop this happening without having to cast length
to a string before printing it out?
推荐答案
使用zfill()
辅助方法将任何字符串,整数或带零的浮点数左移;对于 Python 2.x 和 Python 3.x .
Make use of the zfill()
helper method to left-pad any string, integer or float with zeros; it's valid for both Python 2.x and Python 3.x.
示例用法:
print str(1).zfill(3);
# Expected output: 001
说明:
应用于值时,当初始 string 值的长度小于所应用的 width 值的长度时,zfill()
返回一个用零填充的值,否则为 string 的初始值.
When applied to a value, zfill()
returns a value left-padded with zeros when the length of the initial string value less than that of the applied width value, otherwise, the initial string value as is.
语法:
str(string).zfill(width)
# Where string represents a string, an integer or a float, and
# width, the desired length to left-pad.
这篇关于如何在Python 3中使用前导零填充字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!