4

I want to select elements from a layer. The field I use is a string/character field. My code is as follows:

expr = QgsExpression(ur'"myField" = \'valueILookFor\'')
it = myLayer.getFeatures(QgsFeatureRequest(expr))
ids = [i.id() for i in it]
myLayer.setSelectedFeatures (ids)

I do know that the error lies in the first line, as I've already used the rest of the code (which is from stackexchange) for selecting values.

Apparently this does not select any value. I have tried to replace the "=" with a "LIKE" without more success.

François
  • 73
  • 4

2 Answers2

4

You can also use triple-quoted strings, this means you can leave your double quotes and single quotes (apostrophes) un-escaped.

Can make things a little tricky to maintain, so if you can, leave one space padding at the start and end, like so

expr = QgsExpression(""" "my_field" like '%something%' """)
Steven Kay
  • 20,405
  • 5
  • 31
  • 82
2

Try something like this:

expr = QgsExpression( " \"myField\"= 'valueILookFor' " )

or

expr = QgsExpression( " \"myField\" LIKE 'valueILookFor' " )

Have to be careful with the quotes. Also, you can just use u'string instead of ur'string'.

Joseph
  • 75,746
  • 7
  • 171
  • 282