How do I calculate a field using sequential numbers but maintain a defined number of digits?

297
3
Jump to solution
12-20-2019 05:55 AM
JimNoble
New Contributor III

I'd like to create a field of sequential numbers starting at 001 counting all the way until 322. Every number must be 3 digits. How do I do this?

Thank you all for your help.

0 Kudos
1 Solution

Accepted Solutions
JakeSkinner
Esri Esteemed Contributor

Hi James,

You can do this using the Field Calculator.  Here is an example:

rec=0
def autoIncrement():
 global rec
 pStart = 1 #adjust start value, if req'd 
 pInterval = 1 #adjust interval value, if req'd
 if (rec == 0): 
  rec = pStart 
 else: 
  rec = rec + pInterval 
 if len(str(rec)) == 1:
     return "00" + str(rec)
 elif len(str(rec)) == 2:
     return "0" + str(rec)
 elif len(str(rec)) == 3:
     return str(rec)

View solution in original post

3 Replies
JakeSkinner
Esri Esteemed Contributor

Hi James,

You can do this using the Field Calculator.  Here is an example:

rec=0
def autoIncrement():
 global rec
 pStart = 1 #adjust start value, if req'd 
 pInterval = 1 #adjust interval value, if req'd
 if (rec == 0): 
  rec = pStart 
 else: 
  rec = rec + pInterval 
 if len(str(rec)) == 1:
     return "00" + str(rec)
 elif len(str(rec)) == 2:
     return "0" + str(rec)
 elif len(str(rec)) == 3:
     return str(rec)

JimNoble
New Contributor III

Thanks Jake. That's perfect!

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Another approach, instead of using global variables, is to use a generator:

Code Block:

def gen(x=0):
    while True:
        yield "{:0=3}".format(x)
        x+=1

g = gen()

Expression:

next(g)