在每个整数的开头添加 0

Add 0's at the beginning of each integer

我有很多文件(大约400,000),其标识是一个六位数字。但是如果数字小于 6 位,那么我们在数字的开头添加 0。例如文件标识为25,则文件名为000025.txt。我想知道如何检测一个数字的位数以及如何在数字开头添加正确数量的 0。部分代码如下:

import numpy as np
fake_id = np.random.randint(0,400000,400000)
id_change = fake_id[fake_id < 100000]
#### so for fake_id < 100000, we need to find out how many digits of the id, and then we can add the correct number of zeros at the beginning.

感谢您的帮助。

您可以只使用 str.format 到 "pad" 前导零,直到您的号码长为 6 位数字

>>> '{:06d}'.format(25)
'000025'
>>> '{:06d}'.format(5432)
'005432'
>>> '{:06d}'.format(400000)
'400000'

要将此与您的其余任务结合起来,您还可以使用此技术来构建文件名

>>> '{:06d}.txt'.format(5432)
'005432.txt'