首页 > 解决方案 > 在python中格式化文件名

问题描述

我想根据输入格式化字符串。例如,如果行数为 1,则输出必须为image00001.png,如果行数为 400,则输出为image00400.png

我使用以下方法这样做

filename = "image%05d.png".format(line_count)

但它没有按预期工作。我错过了什么?

标签: pythonstringformat

解决方案


在 Python 3 中,您可以使用 f 字符串:

filename = f'image{line_count:05}.png'


推荐阅读