Select to view content in your preferred language

Iterate with leading zeros

3691
6
02-14-2012 02:42 PM
SamCoggins1
Occasional Contributor
Does anyone out there know how to iterate with leading zeros?

I make a Text field, for example: TEST... and populate the first row with 000000.

The next iteration I want is 000001, then 000002, up 000600.

I can program sequential numbers, but these slice off the leading zeros.

Essentially, I'm trying to make an ordered unique ID field. I then perform a split on 600 cells to return 600 shapefiles, however in the output geodatabase they are ordered 1, 10, 11, 12, 13, ... , 19, 2, 21 and so on, rather than 1, 2, 3, 4, 5, ... , 600.
Tags (2)
0 Kudos
6 Replies
ChrisFox3
Frequent Contributor
Here is one way to do it:

for i in range(1, 600, 1):
    print ((6 -  len(str(i))) * "0") + str(i)
0 Kudos
ChrisSnyder
Honored Contributor
Use the .zfill() method:

>>> test = "1"
>>> test.zfill(10)
'0000000001'
>>>  
0 Kudos
BruceNielsen
Frequent Contributor
Putting Chris's and csny490's answers together:
for i in range(600): #use range(1,601) to get 1 to 600
    str(i).zfill(6)

Will return '000000' to '0000599' (600 strings)
0 Kudos
SamCoggins1
Occasional Contributor
I have written code using the .zfill, my only problem being is that Python doesn't recognise 'fd' as a value of the cell. If I do 'print fd' I get: <geoprocessing describe field object object at 0x07DE6890>... so the script fails at that line. Anyone out there know what to write in place of the ???? given in the script below?

Thanks

My code so far:
import arcpy
from arcpy import env
import os

env.workspace = r'C:\Test\Test.gdb'

wspce = r'C:\Test\Test.gdb'
fc = 'G10'
fdName = "SBCID"
arcpy.AddField_management(wspce + os.sep + fc, fdName, "STRING")

fdList = arcpy.ListFields(wspce + os.sep + fc)

for fd in fdList:
    print fd.name, ">>", fd.type
    print fd
    arcpy.CalculateField_management(wspce + os.sep + fc, fdName, str(fd.????).zfill(3))
    print wspce
    print os.sep + fc
    print fdName
0 Kudos
markdenil
Frequent Contributor
maybe try something like:

arcpy.CalculateField_management(wspce + os.sep + fc, fdName, '"str(!' + fd.name + '!).zfill(3)"', "PYTHON_9.3", "")
0 Kudos
SamCoggins1
Occasional Contributor
Ok, this works and does exactly what I want it to do... Returns a value of 001 to 600 in a field called SBCID. Thanks for your help.

import arcpy
from arcpy import env
import os

env.workspace = r'C:\Test\Test.gdb'

wspce = r'C:\Test\Test.gdb'
fc = 'G10'
fdName = "SBCID"
arcpy.AddField_management(wspce + os.sep + fc, fdName, "STRING")

rows = arcpy.UpdateCursor(fc)

for i, row in enumerate(rows):
    row.SBCID = str(i + 1).zfill(3)
    rows.updateRow(row)
0 Kudos