Selecting features using an expression with PyQGIS
Nowadays (QGIS v3.x)
Get the layer reference:
layer = iface.activeLayer()
Select features by expression:
layer.selectByExpression( "\"ogc_fid\"=482" )
Before QGIS 2.16
Follow these steps:
Get the layer reference:
cLayer = iface.mapCanvas().currentLayer()
Get a featureIterator from an expression:
expr = QgsExpression( "\"ogc_fid\"=482" )
it = cLayer.getFeatures( QgsFeatureRequest( expr ) )
Build a list of feature Ids from the result obtained in 2.:
ids = [i.id() for i in it]
Select features with the ids obtained in 3.:
cLayer.setSelectedFeatures( ids )
NOTE: If you want to set an expression with a string value, you need to add quotation marks to such value, in this way:
expr = QgsExpression( " \"name\" = 'my string' " )
If your string value comes from a variable, you can do this:
myVariable = 'my string'
expr = QgsExpression( " \"name\" = '{}' ".format(myVariable) )
This worked for me on the QGIS Python Console
layer = qgis.utils.iface.activeLayer()
layer .selectByExpression(" \"ogc_fid\" = '{}' ".format(482))
You only need to test it in the GUI interface: "Select by Expression". If it works, you can paste it in your Python code surrounded by double quotes "".
exp = QgsExpression("ogc_fid=482")
If you compare to a string, you can add single quote ''.
exp = QgsExpression("ogc_fid='482'")
It's the same principle in python, it can make the difference between double quote and single quote.