PyQGIS – Selecting Features Containing Specific Text String Using Expressions

featureslayerspyqgisqgsexpressionselect-by-expression

I'm trying to select features with a specific text that I have in an attribute. I used the expressions from the PyQGIS Cookbook but I'm having trouble with the selection because the functions I'm using don't select any feature and I don't get any error message. If I change the selected attribute for another attribute which is formatted as a number instead of text, it works, so I assume the problem is related to the string format. Does anyone know how to use the string attribute correctly, so that it select the records in a specified attribute? Below is the code I'm using:

query = '"System" = "1x10/6 rot"'
selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression(query))
layer.selectByIds([s.id() for s in selection])

I was also trying to use the LIKE operator, but also without success (no selected features):

query = '"System" LIKE "1x10%"'
selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression(query))
layer.selectByIds([s.id() for s in selection])

However, when I use an attribute which is formatted as number it works:

query = '"fid" < 7'
selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression(query))
layer.selectByIds([s.id() for s in selection])

Best Answer

You can use python like this:

layer = QgsProject.instance().mapLayersByName('New scratch layer')[0] #Change to match your layername...
fieldname = 'System' #...and fieldname

for f in layer.getFeatures():
    if f[fieldname]==r'1x10/6 rot':
        layer.select(f.id())

enter image description here