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()
asked Nov 30, 2018 at 16:54
0

2 Answers 2

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()
answered Nov 30, 2018 at 17:02
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)
answered Nov 30, 2018 at 20:16
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.