tags:

views:

465

answers:

6

What would be the best way to increment a value that contains leading zeroes? For example, I'd like to increment "00000001". However, it should be noted that the number of leading zeroes will not exceed 30. So there may be cases like "0000012", "00000000000000099", or "000000000000045".

I can think of a couple ways, but I want to see if someone comes up with something slick.

+1  A: 

Determine the length, convert it to an integer, increment it, then convert it back to a string with leading zeros so that it has the same length as before.

cdonner
+8  A: 
int('00000001') + 1

if you want the leading zeroes back:

"%08g" % (int('000000001') + 1)
ʞɔıu
This solution is good, but not flexible. MarkusQ's solution grows with the variable number of zeroes.
Huuuze
+2  A: 

Presumably, you specifically mean an integer represented as a string with leading zeros?

If that's the case, I'd do it thusly:

>>> a
'00000000000000099'
>>> l = len(a)
>>> b = int(a)+1
>>> b
100
>>> ("%0"+"%dd" % l) % b
'00000000000000100'
Jorenko
+8  A: 

"%%0%ii" % len(x) % (int(x)+1)

-- MarkusQ

P.S. For x = "0000034" it unfolds like so:

"%%0%ii" % len("0000034") % (int("0000034")+1)
"%%0%ii" % 7 % (34+1)
"%07i" % 35
"0000035"
MarkusQ
This does the same thing, without the goofy nested formatting: "%0*i" % (len(x), (int(x)+1))
recursive
Yeah, but I was feeling goofy (just finished reading about the MIA IOCC and...). I almost threw in something like len('+*'+'*+'*int(x))/2 instead of int(x)+1, but I chickened out at the last minute.
MarkusQ
+2  A: 

Store your number as an integer. When you want to print it, add the leading zeros. This way you can easily do math without conversions, and it simplifies the thought process.

Coltin
+13  A: 

Use the much overlooked str.zfill():

str(int(x) + 1).zfill(len(x))
recursive
Much simpler solution.
Huuuze
wow. I think this weekend I'm going to read the Python library reference three times. I can't believe I missed this.
Chris Cameron