I'm working on a program for my work and I'm trying to select multiple power line segments from the same shapefile. I'm having trouble with my SQL syntax to pass both variables on to the selection process in the program. I've tried both the 'or' and 'in' queries. The line of code worked with just one variable, but it still only passes one variable after I added the second one. Any suggestions?

import arcpy

line_val1 = raw_input('Enter Line Number: ')
line_val2 = raw_input('Enter Line Number: ')

expression = str(""" "LINE_NUM_1" = '""" + line_val1 + "'" or """ "LINE_NUM_1" = '""" + line_val2 + "'")

arcpy.SelectLayerByAttribute_management(line_out, "NEW_SELECTION", expression)
  • IMHO string math is an ugly way to format strings, prone to failure. Instead, use the string.format() function: expression = "\"LINE_NUM_1\" = '{:s}' or \"LINE_NUM_1\" = '{:s}'".format(line_val1,line_val2). Also valid: expression = "\"LINE_NUM_1\" in ('{:s}','{:s}')".format(line_val1,line_val2). If in doubt, print the resulting string before using it, and place it in the table selection tool to validate. (Note that this assumes LINE_NUM_1 is a text field -- remove the single quotes if integer, and change the :s to :d.) – Vince Jul 25 at 16:10
  • The field is a text field so your line of code worked great. Thank you for the help and information! – Mark1994 Jul 25 at 16:32

Your or is outside your string.

expression = """ "LINE_NUM_1" = '""" + line_val1 + "' or "\"LINE_NUM_1\" = '" + line_val2 + "'"

I like using IN and format, myself.

""""LINE_NUM_1" IN ('{}', '{}')""".format (line_val1, line_val2)
  • The double quotes around the field name are unnecessary. Once they are dropped you can replace the triple double quotes with single double quotes for an easier to read expression. – PolyGeo Jul 25 at 20:16

This simple one use AND/OR I can't format the script using phone

query1 = " LINE_NUM_1= '" + line1_val + "'"
query2 = "LINE_NUM_2 = '" + line2_val+ "'"
arcpy.SelectLayerByAttribute_management(inputLayer,"NEW_SELECTION", "{0} AND {1} ".format(query1,query2,))
  • 1
    You can code-format text on a phone by using four-spaces on each line or a pair of triple-backquotes (above and below). Unfortunately, this answer is incorrect, because the problem was an OR statement, and your solution is an AND (which won't ever return any rows). – Vince Jul 25 at 18:35
  • Yes you are right he can replace AND by OR in the last line – Younes Idriss Jul 25 at 18:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.