Select By Attribute with Variable

05-02-2021 02:46 PM
New Contributor

I'm trying to iterate through a shapefile with all of the roads in the State of Maine, select only the roads in towns relevant to my project, and then create one new feature class with just those roads. I'm working in Python in a Jupyter notebook and I'm a beginner in both Python and ArcGIS. This code runs, but selects all of the roads, not just those in the town list.


# Create town list
town_list = ['Bangor','Hampden','Veazie','Orono','Brewer','Old Town']

arcpy.env.overwriteOutput = True
for town in town_list:
    select = """TOWN = '{}'""".format(town)


0 Kudos
3 Replies
MVP Frequent Contributor

I'd say there's a few too many quotes in select:

select = "TOWN = '{}'".format(town)

Have you also made it a feature layer to run it on? 

MVP Esteemed Contributor

Of course you could always just use

Split By Attributes (Analysis)—ArcGIS Pro | Documentation

... sort of retired...
0 Kudos
MVP Esteemed Contributor

From another set of eyes; I like f strings over the format() function if you are using Python 3.x:

select = f'TOWN = {town}'


I too wondered what @DavidPike mentioned about a feature layer...


That should just about do it....
0 Kudos