0

I'm trying to use the tool "qgis:selectbyexpression" in one of my own scripts. But it doesn't work. My question is simple: "Why?" :)

My hunch is with the 2nd parameter, the 'expression' (see "HOW I GOT HERE" below).


MY CODE:

Input = QgsMapLayerRegistry.instance().mapLayersByName('Streets')[0]
iface.setActiveLayer(vl)   

processing.runalg('qgis:selectbyexpression', Input, '"STRNAME" = streetslist[k]', 1)

Input = 'Streets', a shapefile with columns of civic numbers, street names, etc.

streetslist = a list I made with a few of the street names that I know match some of the streets in the "STRNAME" column of 'Streets'


HOW I GOT HERE

As with every Q tool from the Toolbox that's new to me I open it up and read up on it in the "Help" tab. Personally, I often find these Help tabs rather unhelpful. Case in point:

enter image description here

It shows the correct order of parameters but without explicit examples of how to fill in them in I'm left guessing.

So I reasoned that the "selectbyexpression" Toolbox tool would work the same as the GUI tool of the same name (top of the Q Project Window, in the Attributes Toolbar? I'm sure you're familiar).

When you run the GUI tool expressions are built something like this:

enter image description here

I assumed the entire 'expression' needs to be surrounded by single quotes because I've seen other tools run that way. Double quotes around the column name and single quotes around the value, right? So I tried the following:

1) '"STRNAME" = 'Main''

This throws the following error:

File "<input>", line 1
    processing.runalg('qgis:selectbyexpression', Input, ' "STRNAME" = 'Hollis' ', 1)                                  
                                               ^

2) ' "STRNAME" = 'Main' '

Exact same error message as previous except oddly the ^ appears to be moved to the right so that rather than pointing at the comma before "Input" it's pointing at the white space before "Input".

I even tried double quotes around the value (the street name) instead of the single quotes:

3) '"STRNAME" = "Main"'

Interestingly, this one runs without error but nothing actually gets selected.

I could go on trying various permutations of single quotes, double quotes, spaces, etc. but I figured the answer is quite simple and someone out there will be kind enough to share.

2

I would try this:

'"STRNAME" = ' + "'Main'"

The trick is to concatenate two strings together, and since each of the strings contains either a single or a double quote, you need to wrap it inside a pair of the opposite type of quotes.

For the selectbyexpression, as you have commented, this would be the equivalent:

processing.runalg('qgis:selectbyexpression', Input, '"STRNAME" = '+ "'"+ streetz[k] +"'", 1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.