Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a numeric string '0000000001' in python?

I have a function getNextSeqNo(). I want it to increment the numeric string when it is called, i.e. 0000000000 to 0000000001, and then to 0000000002. How do I do it?

I have written it as follows:

def __init__(self) :
    self.seq = '0000000000'

def getNextSeqNo(self) :
    self.seq = str(int(self.seq) +1)
    return(self.seq)

I am getting 1 as the output instead of 0000000001.

like image 882
Kat.S Avatar asked Apr 24 '14 13:04

Kat.S


3 Answers

You could convert the string to an int and use something like

self.seq = '%010d' % (int(self.seq) + 1)
return self.seq

If you didn't need self.seq to be a string you could do

def __init__(self) :
    self.seq = 0

def getNextSeqNo(self) :
    self.seq += 1
    return '%010d' % self.seq
like image 116
Khaelex Avatar answered Oct 30 '22 16:10

Khaelex


Quickest and easiest, although certainly not clearest:

str(int('9' + self.seq) + 1)[1:]

It works by adding a leading digit before converting to integer, to retain all the leading zeros, then stripping off that leading digit after converting back to string. It has the advantage of not requiring you to know in advance how many digits are required.

like image 30
Mark Ransom Avatar answered Oct 30 '22 15:10

Mark Ransom


Format your number, with format():

self.seq = format(int(self.seq) + 1, '010d')

better still, don't store a string but an integer and return the formatted version:

def __init__(self):
    self.seq = 0

def getNextSeqNo(self):
    self.seq += 1
    return format(self.seq, '010d')

Format with 010d outputs your integer as a 0-padded string with 10 characters:

>>> format(0, '010d')
'0000000000'
>>> format(42, '010d')
'0000000042'
like image 37
Martijn Pieters Avatar answered Oct 30 '22 16:10

Martijn Pieters