Nowadays : QGIS 3.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) )