Frage

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.

War es hilfreich?

Lösung

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

Andere Tipps

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'

There are many answers. Here is another one:

import string
seq = 1
string.zfill(seq, 10)
# '0000000001'
# works with strings too:
string.zfill('00001', 10)
# '0000000001'

or

seq = 1
str(seq).zfill(10)
# '0000000001'

Note how string.zfill takes directly an int as parameter.

You can do it using string formatting:

new_s = '{:0>{}}'.format(str(int(s)+1),len(s))

print new_s

You should store the current numeric value as an int instead, and generate strings from that on the fly.

>>> i = 0
>>> "{0:010d}".format(i)
'0000000000'

>>> i += 1
>>> "{0:010d}".format(i)
'0000000001'

It's a bad idea to store numeric values in a string form just because that's how you'd like to present them (or use in some context where a string is required).

Then getNextSeqNo becomes this:

def getNextSeqNo(self):
    ret = "{0:010d}".format(self._seq_i)
    self._seq_i += 1
    return ret

The best thing is, not to keep the sequence in a string, but format the sequence number when needed:

class SeqNo:
    def __init__(self):
        self.seq = 0

    def next(self):
        self.seq += 1
        return '%10d' % self.seq
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top