Sequential field calculation with Python

3216
4
Jump to solution
06-01-2016 07:35 AM
KatyW
by
New Contributor III


I'm trying to field calculate some records that have a null value.  I used the following code from the ESRI help section on sequential calculations.  It worked!  Now I need to modify the script a bit.  This code gives me a sequential order of single digits.  I would like to have some zeros before the new assigned digit.  0001 instead of just 1.  How do I add the three zeros before the assigned digit?  I would like a four digit value in the end.  0001, 0002, 0003, etc.

Thanks!

Here's the python code I used:

Parser:

Python

Expression:

autoIncrement()

Code Block:

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

    return rec

0 Kudos
1 Solution

Accepted Solutions
ChristianWells
Esri Contributor

Hi Katherine, you can return these values as strings with numbers prefixed by zeros using the zfill method.

Python String zfill() Method

num = 1
str(num).zfill(4)

'0001'

View solution in original post

4 Replies
ChristianWells
Esri Contributor

Hi Katherine, you can return these values as strings with numbers prefixed by zeros using the zfill method.

Python String zfill() Method

num = 1
str(num).zfill(4)

'0001'
KatyW
by
New Contributor III

Where do I add this into my code?  Or is this string code a separate process?

0 Kudos
KatyW
by
New Contributor III

Here is the solution!

Use the original script to sequentially order.  After that is done field calculate again using the field you wish to add the extra digits to.  Then you can choose the string type as .zfill and add as many zeros as you would like.  I attached a screen shot to help clarify.  This gave me the result I was looking for!

Python.jpg

ChristianWells
Esri Contributor

Fantastic! Glad this worked out for you.

0 Kudos