Using Variable for Where Clause in search cursor

7526
5
Jump to solution
03-30-2015 06:31 PM
RyanTucker1
New Contributor II

How do I go about using a variable from a raw_input for the where clause in da.SearchCursor?

I can't seem to get the syntax correct

Code:

import arcpy
from arcpy import env
env.workspace=r"F:\GEOG_488\Final_Project_Data\FinalProject488.gdb"
fc="PARCELS" #Create variable for feature class
tc="ADDRESS_TEST_20"  #Create variable for table

HouseNumber = int(raw_input("Enter Address Number: ")) #User input House Number
print "Situs Addresses with "+ str(HouseNumber)+" for the Situs Number:"


cursor = arcpy.da.SearchCursor(tc,["ADDR"],'"SA_House_Number"= HouseNumber') #Create search cursor where records = HouseNumber
for row in cursor:
    print "Situs Address with House Number"+str(HouseNumber)":",row[0]

del row, cursor

Thanks for any help.

0 Kudos
1 Solution

Accepted Solutions
ModyBuchbinder
Esri Regular Contributor

'"SA_House_Number" = ' + str(HouseNumber)

When the HouseNumber is inside the quotes it is not recognized as variable

I am not sure you have to put the attribute name (SA_House_Number) in quotes in the new versions.

View solution in original post

5 Replies
DarrenWiens2
MVP Honored Contributor

Escape HouseNumber from the where clause string.

ModyBuchbinder
Esri Regular Contributor

'"SA_House_Number" = ' + str(HouseNumber)

When the HouseNumber is inside the quotes it is not recognized as variable

I am not sure you have to put the attribute name (SA_House_Number) in quotes in the new versions.

JoshuaBixby
MVP Esteemed Contributor

I encourage you to learn about Python string formatting (Format String Syntax).  It is extremely robust.

cursor = arcpy.da.SearchCursor(tc,["ADDR"],"SA_House_Number = {}".format(HouseNumber))

RyanTucker1
New Contributor II

Thank you all for your help. It now works using both the suggestion from Mody and Joshua.

I'm now reading up on string formatting.

Thanks again!

Ryan

0 Kudos
danashney
New Contributor III

Joshua Bixby deserves a beer or milk shake if a teetotaler.

+1 for string formatting.

0 Kudos