Saturday 30 March 2019

arcgis desktop - Sequential IDs with field calculator: Pad a prefixed field to specific length


I have an ID field that is a text datatype. The IDs in the field have a prefix, and are padded with zeros to always be a specific length. Examples:



  • INSP000098

  • INSP000099

  • INSP000100

  • INSP000101



I would like to use the Field Calculator to generate sequential IDs for new records (records are batch loaded from various sources by the thousands).


I have a python script that almost does this:


Modified from: Create sequential numbers in a field using Python in the Field Calculator


prefix = "INSP0000"
lastnumber=97

rec=0
def autoIncrement():
global rec
pStart = 1

pInterval = 1
if (rec == 0):
rec = 1 + lastnumber
else:
rec += pInterval
return prefix+str(rec)



autoIncrement()


Steps:



  1. Manually enter the prefix (with zeros for padding)

  2. Manually enter the last number in the existing IDs

  3. Run the script


Result:


Unfortunately, the tool isn't smart enough to dynamically adjust for the difference in the number of digits between numbers (99 to 100, etc.):



  • INSP000098


  • INSP000099

  • INSP0000100 << Problem: too many zeros/digits

  • INSP0000101


How can I use the field calculator to generate sequential, prefixed IDs that are padded with zeros to a specific length?


I'm not married to Python; VBScript would be an acceptable alternative.



Answer



rec=97
def withPads():
global rec

rec+=1
return 'INSP%s' %str(rec).zfill(6)
#------------
withPads()

OUTPUT:


enter image description here


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...