0

I am able to use UpdateCursor to find and delete rows if a field contains part of a string (code below works). Now I want to do the opposite--if part of this string is not in my field, I want to delete the row. Is there a "not_in" function/syntax?

with arcpy.da.UpdateCursor(mySHP, ['OID@', 'Comments']) as cursor:
    for row in cursor:
        if 'this phrase' in row[1]:
            cursor.deleteRow()
5

Either add a not to the if statement:

with arcpy.da.UpdateCursor(mySHP, ['OID@', 'Comments']) as cursor:
    for row in cursor:
        if 'this phrase' not in row[1]:
            cursor.deleteRow()

or you could add an else block:

with arcpy.da.UpdateCursor(mySHP, ['OID@', 'Comments']) as cursor:
    for row in cursor:
        if 'this phrase' in row[1]:
            pass
        else:
            cursor.deleteRow()
1

You can also use a where clause to limit the rows returned by the cursor. This should be faster since not all rows are read by the cursor.

import arcpy

mySHP = r'C:\shapefile.shp'
commentfield = 'Comments'
sql = """{0} NOT LIKE '%this frase%'""".format(arcpy.AddFieldDelimiters(mySHP,commentfield))

with arcpy.da.UpdateCursor(mySHP, commentfield, sql) as cursor:
    for row in cursor:
        cursor.deleteRow(row)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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