在每个整数的开头添加0

时间:2017-04-18 16:43:35

标签: python numpy digit

我有很多文件(大约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.

感谢您的帮助。

1 个答案:

答案 0 :(得分:6)

您只需使用str.format“填充”前导零,直到您的号码长度为6位

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

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

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