Monday, April 25, 2011

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 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.

From stackoverflow
  • 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.

  • int('00000001') + 1
    

    if you want the leading zeroes back:

    "%08g" % (int('000000001') + 1)
    
    Huuuze : This solution is good, but not flexible. MarkusQ's solution grows with the variable number of zeroes.
  • 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'
    
  • "%%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"
    
    recursive : This does the same thing, without the goofy nested formatting: "%0*i" % (len(x), (int(x)+1))
    MarkusQ : 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.
  • 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.

  • Use the much overlooked str.zfill():

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

0 comments:

Post a Comment