1

I know this question has been answered but I am not seeing an adaptation that I can understand. I am trying to use a numeric variable in a where clause and just having a hard time figuring it out.

fc1 = "L:\ENGINEERING\collind\ArcGIS\Default.gdb\sedaSampleHistory"
fieldname = "pocid"
delimfield = arcpy.AddFieldDelimiters(fc1, fieldname)
pocidCnt = 3
cursor = arcpy.da.SearchCursor(fc1, ["pocid", "cl2total"], delimfield + " = pocidCnt ")

I have tried all kinds of ways to get pocidCnt to work in the where clause and I am not having any luck. If I write it as

cursor = arcpy.da.SearchCursor(fc1, ["pocid", "cl2total"], delimfield + " = 3 ")

it works fine.

What am I doing wrong?

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked Aug 22, 2014 at 16:56
2
  • Have you tried not passing it as a string in quotes and just putting the variable name with no quotes:-------cursor = arcpy.da.SearchCursor(fc1, ["pocid", "cl2total"], delimfield + pocidCnt ) Commented Aug 22, 2014 at 17:02
  • Thanks for the quick response... when I make that change I get Runtime error Traceback (most recent call last): File "<string>", line 10, in <module> TypeError: coercing to Unicode: need string or buffer, int found Commented Aug 22, 2014 at 17:08

1 Answer 1

5

Your code fails because the variable name (pocidCnt) is inside a string and is therefore being taken literally: the final query being used is "pocid" = pocidCnt, where pocidCnt is clearly not a number that can be matched. You can substitute the value represented by the pocidCnt variable into the query string in the following ways:

cursor = arcpy.da.SearchCursor(fc1, ["pocid", "cl2total"], delimfield + " = " + str(pocidCnt))

or, preferably:

cursor = arcpy.da.SearchCursor(fc1, ["pocid", "cl2total"], "{0} = {1}".format(delimfield, pocidCnt))
answered Aug 22, 2014 at 17:07
2
  • Thank you. Both of those work. So I guess what I was trying to do was insert an int into an expression that is a string. Is that correct? Commented Aug 22, 2014 at 17:13
  • Yes, the value of pocidCnt must be converted from an int to a string (i.e. from 3 to "3") before it can be combined with the rest of the query string. The str() function achieves this clumsily, while the string .format() method is a little more graceful about it. Commented Aug 22, 2014 at 17:16

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.