5

I want to use a loop to select values with expression in a layer. The values contain the letters OS and a number (example: "OS1","OS2"). I want to use the loop to increase the number to use my processing script on the features separately. How do I use the selectbyexpression() in the right way to increase the number in a loop?

i = 1
OSnumber = str(i)
OSname = 'OS'+OSnumber

OS_trace = Map+'OS_tracés.shp'
layer = iface.activeLayer()
layer.selectByExpression("attributename = 'Osname'")

1 Answer 1

10

You can use the following script structure:

layer = iface.activeLayer()

end_number = 5 # OS1, OS2, OS3, OS4, OS5
attribute_name = "attribute_name" # field name containing OS values

for i in range(end_number):
    osname = f"OS{i+1}"
    layer.selectByExpression(f"{attribute_name} = '{osname}'")

    # Do whatever with the selected features
    # For example:
    print(layer.selectedFeatureCount())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.