Reputation: 73
I just made a function to generate a list of running ids between a given range. IDs begin with an alphabet and follow with 5 numbers (e.g. A00002). The function below works, but I was wondering if there was a cleaner way to do this. Thanks!
def running_ids(start, end):
list = []
start = int(start[1:])
end = int(end[1:])
steps = end - start
def zeros(n):
zeros = 5 - len(str(n))
return zeros
while start <= end:
string = "A" + "0"*zeros(start) + str(start)
list.append(string)
start += 1
return list
print running_ids('A00001', 'A00005')
['A00001', 'A00002', 'A00003', 'A00004', 'A00005']
Upvotes: 0
Views: 341
Reputation: 10252
def running_ids(start, end):
t = start[0]
low = int(start[1:])
high = int(end[1:]) + 1
res = []
for x in range(low, high):
res.append(t + '{0:05d}'.format(x))
return res
print(running_ids('A00001', 'A00005'))
Upvotes: 0
Reputation: 88198
Use a generator. This way you can generate the numbers as needed and not store them all at once. It also maintains the state of your counter, useful if you start building large projects and you forget to add one to your index. It's a very powerful way of programming in Python:
def running_id():
n = 1
while True:
yield 'A{0:05d}'.format(n)
n += 1
C = running_id()
for n in xrange(5):
print next(C)
Giving:
A00001
A00002
A00003
A00004
A00005
Upvotes: 3
Reputation: 239573
You can use the builtin format
method
print "A" + format(1, "05d") # A00001
print "A" + format(100, "05d") # A00100
Or you can use str.zfill
method like this
print "A" + str(1).zfill(5) # A00001
print "A" + str(100).zfill(5) # A00100
Upvotes: 1
Reputation: 310049
You could just use simple builtin string formatting:
>>> 'A%05d'%1
'A00001'
>>> 'A{0:05d}'.format(1)
'A00001'
Upvotes: 3