Does anyone know the correct syntax for the selectbyexpression processing algorithm for selecting MTFCC's? This is what I have right now, but it doesn't work so I'm guessing my problem lies in the syntax for the "expression" variable.

layer = qgis.utils.iface.activeLayer()
expression = '"MTFCC" = "H3010"'
processing.runalg("qgis:selectbyexpression", layer, expression, 0)

When I select by expression using the GUI, it shows something like "MTFCC" + "H3010" and gives me an output preview of 'S1400H3010' and I don't understand. Anything else I try just gives me an "expression invalid" error.

I am using pyQGIS v2.14.0

  • try expression = QgsExpression(" \"MTFCC\" = \"H3010\" ")
    – dof1985
    Jul 11, 2016 at 6:58
  • that gives me a "Problem executing algorithm: syntax error, unexpected LT" error in a small window
    – Eli Reyner
    Jul 11, 2016 at 17:48

1 Answer 1


Here it is. Changes to your code are provided below, followed by an explanation.

layer = qgis.utils.iface.activeLayer()
expression = "/"MTFCC/" = /"H3010 /" "  # note that I've modified this line
processing.runalg("qgis:selectbyexpression", layer, expression, 0)

Using processing.alghelp("qgis:selectbyexpression") I have seen that the function uses QString and not an Expression as a parameter. Thus there was no need to use QgsExpression as I've suggested before. Nevertheless, your syntax was wrong, since you misused ".

In general when you build a python string you will use "..." to define the places a string starts and ends. Similarly, you can involve both strings and variables to build a more complex expression, e.g. "This string involves a" + variable + ", right?".

In your case you wanted an expression that calls a field, which in SQL looks like that: "FieldName1" = "FieldName2". Python however reads two strings instead of one expression. The common slash (/) is used as an "exit" sign, and it indicates that the symbol that follows is a part of a string, and not a python function. Using / " causes the interpreter to ignore any commands / activities related to this specific ". Finally it leads to this python expression: " /"FieldName1/" = "/FieldName2/" ".

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.