Django / Python: how can I do the following numerical increase (not in the database)

I would like to create a number like:

000000000001 

to save to the database. Obviously, I canโ€™t increase this method (I donโ€™t think) in the database, so Iโ€™m looking for the most efficient method to pull the previous number from the database and increase it by 1 to create the following record:

 000000000002 

etc.

If I save the first number manually, can I do some manual typing to delay its number of zeros? I donโ€™t even know where to start.

0
source share
2 answers

All leading zeros are just formatting.

 >>> "%012d" % ( 1, ) '000000000001' >>> "%012d" % ( 2, ) '000000000002' 

Use a regular integer and format it to have many leading zeros.

+5
source

This is actually a very complex way to do this using the itertools library and generator function.

 from itertools import product, imap def stringdigit(num_digits=10, start = None): """A generator function which returns string versions of a large iterated number with leading zeros. start allows you to define a place to begin the iteration""" treatfun = lambda x: ''.join(x) for n in imap(treatfun, product('0123456789', repeat = num_digits)): if start == None or n > start: yield n 

This creates an iterator that will return a null-filled string form. It works using a product function that iteratively returns duplicate combinations from iterable in "sorted order". The num_digits argument indicates how many total digits you want to return. start indicates the place to start the iteration (say, if you want to start with 1111111).

product ships with python 2.6 release. If you are using something before this for some reason, use this as a product definition. Taken from the documentation here .

 def product(*args, **kwds): # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod) 

You can use this function in a for-loop as interator:

 for num in stringdigit(num_digits = 7): #do stuff with num 

Hope this helps. -Will be

+1
source

All Articles