Select Layer by Attribute in ArcPy

270
3
Jump to solution
04-10-2018 12:35 PM
MohammadrezaNikfal1
Occasional Contributor

I am working on a simple application. The user can choose either Numeric values or string values to select (i.e. valName). However if you write the where clause like this:

arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION", FieldName + opName + "'" + valName + "'")

It doesn't work for numbers and if you write like this:

arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION",FieldName + opName + valName)

  It doesn't work for strings. 

Any simple solution without if condition?

0 Kudos
1 Solution

Accepted Solutions
MohammadrezaNikfal1
Occasional Contributor

This worked for me:

if type(valName) is str or type(valName) is unicode:
   whereClause = FieldName + opName + "'" + valName + "'"
else:
   whereClause = FieldName + opName + str(valName)
arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION", whereClause)

View solution in original post

0 Kudos
3 Replies
RandyBurton
MVP Regular Contributor
"{} {} '{}'".format(FieldName,opName,valName) if type(valName) is str else "{} {} {}".format(FieldName,opName,valName)

You might try something like:

MohammadrezaNikfal1
Occasional Contributor

This worked for me:

if type(valName) is str or type(valName) is unicode:
   whereClause = FieldName + opName + "'" + valName + "'"
else:
   whereClause = FieldName + opName + str(valName)
arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION", whereClause)
0 Kudos
RandyBurton
MVP Regular Contributor

You can also use "in"

if type(valName) in (str, unicode) else ...