Hua*_*ang 0 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.
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
您可以使用str.format前导零填充"填充",直到您的数字为6位数
>>> '{:06d}'.format(25)
'000025'
>>> '{:06d}'.format(5432)
'005432'
>>> '{:06d}'.format(400000)
'400000'
Run Code Online (Sandbox Code Playgroud)
要将此功能与其余任务结合使用,您还可以使用此技术来构建文件名
>>> '{:06d}.txt'.format(5432)
'005432.txt'
Run Code Online (Sandbox Code Playgroud)