How to increment a value with leading zeroes?

后端 未结 7 1474
一整个雨季
一整个雨季 2021-02-05 22:23

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

相关标签:
7条回答
  • 2021-02-05 22:49

    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.

    0 讨论(0)
  • 2021-02-05 22:50
    int('00000001') + 1
    

    if you want the leading zeroes back:

    "%08g" % (int('000000001') + 1)
    
    0 讨论(0)
  • 2021-02-05 22:50

    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 讨论(0)
  • 2021-02-05 22:51

    Use the much overlooked str.zfill():

    str(int(x) + 1).zfill(len(x))
    
    0 讨论(0)
  • 2021-02-05 22:51

    "%%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"
    
    0 讨论(0)
  • 2021-02-05 23:00

    "my code is in c" int a[6]={0,0,0,0,0,0},i=5,k,p; while(a[0]!=10) { do { for(p=0;p<=i;p++) printf("%d",a[p]); printf("\n"); delay(100); a[i]++; }while(a[i]!=10); for(k=0;k<=i;k++) if(a[i-k]==10) { a[i-(k+1)]++; a[i-k]=0; } }

    0 讨论(0)
提交回复
热议问题