2

I am new to Python.

I am using the name of my Feature Classes to populate an attribute field with update cursors, but I am trying to add a dash 2 spaces from the left. For example the feature class is name OB619 and I need to populate the ID field as OB-619. I was able to get the update cursor to take the name of the Feature Class, but I haven't been able to figure outnhow to use splicing in the cursor to add the dash.

arcpy.env.workspace = r'\\\Public\OB_Test_3.gdb\Test1'

def makeFullPath(path, name):
    return path + "\\" + name


file_name_field = "ID"
fieldname2 = "FLOATABLES"
fieldname3 = "PATHOGENS"
fieldname4 = "NITROGEN"
fieldname5 = "OWNERSHIP"



feature_classes = arcpy.ListFeatureClasses()

fieldsList = [file_name_field, fieldname2, fieldname3, fieldname4, fieldname5 ]

for fc in feature_classes:
    existing_fields = [f.name for f in arcpy.ListFields(fc)]
    if fieldsList not in existing_fields:
       arcpy.management.AddField(fc, file_name_field, 'TEXT', field_length=200)
       arcpy.management.AddField(fc, fieldname2, 'TEXT', field_length=50)
       arcpy.management.AddField(fc, fieldname3, 'TEXT', field_length=50)
       arcpy.management.AddField(fc, fieldname4, 'TEXT', field_length=50)
       arcpy.management.AddField(fc, fieldname5, 'TEXT', field_length=50)
       # write the file name into each row of the file name filed

    with arcpy.da.UpdateCursor(fc, [file_name_field]) as uc:
        for row in uc:
            uc.updateRow([str(fc)])
    del row, uc

1 Answer 1

3

To add a dash 2 spaces from the left you can do:

fc= fc[:-2] + "-" + fc[-2:]

Based on your question and example I'm not sure exactly what your goal is, but I think you would want to replace the cursor with the following to get your desired output:

with arcpy.da.UpdateCursor(fc, [file_name_field]) as uc:
        for row in uc:
            row[1] = fc[:-2] + "-" + fc[-2:]
            cursor.updateRow(row) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.