python - 如何在 Python 3 中用前导零填充字符串

标签 python python-3.x math rounding

我正在尝试在 Python 3 中制作 length = 001 但每当我尝试将其打印出来时,它都会截断没有前导零的值(length = 1) .我将如何阻止这种情况发生而不必在打印出来之前将 length 转换为字符串?

最佳答案

利用 zfill() 辅助方法来左填充任何字符串、整数或 float ;它对 Python 2.x 都有效和 Python 3.x .

需要注意的是,Python 2 是 no longer supported .

示例用法:

print(str(1).zfill(3))
# Expected output: 001

说明:

当应用于一个值时,zfill() 返回一个值,当初始 string 值的长度小于所应用的 width 值,否则为初始 string 值。

语法:

str(string).zfill(width)
# Where string represents a string, an integer or a float, and
# width, the desired length to left-pad.

关于python - 如何在 Python 3 中用前导零填充字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39402795/

相关文章:

python - 使用多处理创建同一进程的多个实例

python-3.x - 为什么 lru_cache 比作为以下斐波那契计算器的字典实现的缓存慢?

python - 从 Python 3 中的文件生成的列表中查找字符串

math - 在 Three.js 中根据对象的旋转来移动对象

c++ - fmod 还是不 fmod?

php - 如何使用文件 IO 最好地将 python 字典传递给 PHP

python - pandas.DataFrame.groupby.nunique() 不会删除 groupby 列。这是一个错误吗?

math - 避免指数计算中的舍入误差

python - 在 Django 模型中,外键字段如何知道与其他模型中的哪个字段匹配?

python - 无法使用 set 剔除重复结果