I'm trying to select features from a polygon layer where a specific string value ('yes') is found in a field called "result" and buffer them. My script can select features with a specific integer value in the "id" field and buffer them successfully, but doesn't appear to work for a string value in the "result" field; a buffer layer is produced but contains no features or geometry.

I'm relatively new to PyQGIS.

from qgis.core import *
from qgis.utils import *

# Set output file
output_fn = 'C:/Test/Buffer.shp'

# Set input layer to select features from
layer = iface.activeLayer()

# Select features by expression
#layer.selectByExpression('"result"=yes') # <- Desired selection doesn't work
layer.selectByExpression('"id"=2') #        <- Undesired but produces a buffer of the specified feature

# Buffer selected feature(s)
{'INPUT': QgsProcessingFeatureSourceDefinition(layer.id(), selectedFeaturesOnly=True, featureLimit=-1,\
'OUTPUT': output_fn})
# Add output layer to layer tree
iface.addVectorLayer(output_fn, '', 'ogr')

Below is an image of the two features in the layer with the attribute table. Successfully buffered via layer.selectByExpression('"id"=2') version of the script.

Output from selectByExpression('"id"=2')

Below is the non-result of using the layer.selectByExpression('"result"=yes') version of the script. In both scenarios, a Buffer layer is added to the Layer tree, though in this version it is empty. I can only narrow it down to there being a simple but elusive problem with the expression here because a selection has not occurred when looking at the attribute table. The key difference being that the first scenario involves an integer field, and this scenario a string field. Extension question (related): are there any good sources for constructing valid expressions with the selectByExpression method?

Output from layer.selectByExpression('"result"=yes')


1 Answer 1


You need to use a single quote in the expression this way: '"result"=\'yes\''. Because yes is a string.

Integer value works because no need ' for integers.


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.