I want that one variable takes input from the user and then we compare the value to the attribute.

val = input("Ask user for something.")

arcpy.SelectLayerByAttribute_management("Sample", "NEW_SELECTION", """ "ATTRIBUTENAME" = 'val' """)

In this as we have to put apostrophes around "val" it takes it as string not as variable whose value we want to compare. So any way by which we can do this?

3 Answers 3


You'll make life simpler in the future by using Add Field Delimiters. This will work for shapefiles, feature classes in a file geodatabase, personal geodatabase, etc. You might find that str.format() also makes building strings with quotation marks easier to read/write.

val = raw_input("Ask user for something:\n")
fc = "Sample"
field = arcpy.AddFieldDelimiters(fc, "ATTRIBUTENAME")
selection = "{field} = '{val}'".format(field=field, val=val)
arcpy.SelectLayerByAttribute_management(fc, "NEW_SELECTION", selection)

I've not tried doing such in that particular circumstance, but normally when doing similar work in python, I would do something like the following:

val = raw_input("Ask user for something.")

selection = str(""" "ATTRIBUTENAME" = '""" + val + "'")

arcpy.SelectLayerByAttribute_management("Sample", "NEW_SELECTION", selection)

Also note, that, at least in my version of python, if you just do val = input("Ask user for something."), you have to understand that the user will have to not type user answer, but rather will have to type "user answer" or 'user answer' for it to be accepted by python and interpreted as an input string. This is because input() takes the user supplied value and tries to execute it as if it were just another line of pyton code in the script itself. However, to get around this, you can use raw_input() which reads the user entered value as a string.


A safer way to do this would be:

val = raw_input("Ask for something. ")

query = """ "ATTRIBUTE_NAME" = '%s'"""%val

arcpy.SelectLayerByAttribute_management("Sample", "NEW_SELECTION", query)

In this case, using %s will convert the value you get to string. This way, if the user inputs an integer, the + operator won't fail to create the query.

If you wanted to be sure it would work for any given data type, you could also use AddFieldDelimeters to handle the attribute name regardless of what the source data type was.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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