Select to view content in your preferred language

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

742
3
12-20-2019 05:55 AM
by
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.

1 Solution

Accepted Solutions
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)‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍``````

3 Replies
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)‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍``````

by
New Contributor III

Thanks Jake. That's perfect!

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)‍``