[GIS] Set up definition query with variable

arcpydefinition-query

I am writing a script which supposed to get a value for a field from user and use that value for a definition query.

If I write it without variable, it works:

my_Layer.definitionQuery = "IncidentName = 'Hospital Rd, Kurri Kurri'"

If I this, it does not work:

AA = 'Hospital Rd, Kurri Kurri'
my_Layer.definitionQuery = "IncidentName = AA"

The definition query is set to string AA, and not the value set I assigned to it.

Best Answer

You have just made AA a literal string by quoting it. You have not set up the quotes correctly to make the single quotes literal within your AA variable, plus you have not concatenated the variable value to the string or added it to the string using the .format syntax. There are several ways to do it correctly. For example it could be done this way:

AA = "'Hospital Rd, Kurri Kurri'"
my_Layer.definitionQuery = "IncidentName = {}".format(AA)

Alternatively it could be done this way, which would make it easier for the user to input a value that did not have to be properly quoted:

AA = "Hospital Rd, Kurri Kurri"
my_Layer.definitionQuery = "IncidentName = '{}'".format(AA)
Related Question