Skip to content Skip to sidebar Skip to footer

How To Increment A Value With Leading Zeroes?

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 leadin

Solution 1:

Use the much overlooked str.zfill():

str(int(x) + 1).zfill(len(x))

Solution 2:

int('00000001') + 1

if you want the leading zeroes back:

"%08g" % (int('000000001') + 1)

Solution 3:

"%%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"

Solution 4:

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'

Solution 5:

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.

Post a Comment for "How To Increment A Value With Leading Zeroes?"