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
.
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
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With