A handy wildcard tip

As you know, the arcpy module provides functions built specifically for listing data so it can be iterated through during processing. All these list functions can be passed a wildcard argument which filters what is returned. For example, if you only require feature classes that start with a prefix of “tax”, you would do this:

# Set the workspace. List all feature classes that start with 'tax'.
arcpy.env.workspace = "d:/stjohns/localgovernment.gdb"
fcs = arcpy.ListFeatureClasses("tax*")

However, what if you wanted to retrieve all feature classes which do not start with “tax”? Here is a handy trick for doing it:

arcpy.env.workspace = "d:/stjohns/localgovernment.gdb"
fcs = [fc for fc in arcpy.ListFeatureClasses() if not fc.startswith('tax')]

If “tax” was a suffix, use endswith:

fcs = [fc for fc in arcpy.ListFeatureClasses() if not fc.endswith('tax')]

6 thoughts on “A handy wildcard tip

  1. Nice post. A nice thing that can be done with startswith and endswith is to feed it a tuple of values to be matched. For example, if you wanted to match (or not match) feature classes starting with tax or starting with cadastral then you could use fc.startswith((‘tax’, ‘cadastral’)).

  2. import arcpy
    … from arcpy import env
    … env.workspace = r”C:\Evaluation.gdb”
    … fcs = [fc for fc in arcpy.ListFeatureClasses()if not fc.endswith(‘_city’)]

    it does not work

    • the list comp doesn’t work well for the delete_management tool. This is because that tool takes a single dataset as input not a list (as you’re passing it with the ‘fcs’ variable).

      You’d just want to do a regular for loop in your case.

      for fc in arcpy.ListFeatureClasses():
      if not fc.endswith("_city"):

    • Have a look at python’s for loop. Of course use with caution.

      Make sure you run your script a few times with a print statement inside the loop to make sure you’ll be deleting the data you want to delete.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s