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.

2 Answers 2


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%' """)

Try something like this:

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


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

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

  • Does not work either. I tried various combinaisons of these.
    – François
    Jan 27, 2016 at 14:18
  • 2
    does it work with a triple quoted string? expr = QgsExpression( """ "myField"= 'valueILookFor' """)
    – Steven Kay
    Jan 27, 2016 at 14:24
  • @François - Apologies, I missed out the single quotes as it initially worked for numbers. Should work now for strings also.
    – Joseph
    Jan 27, 2016 at 14:37
  • @StevenKay - The triple quote method should also work, consider posting your comment as an answer =)
    – Joseph
    Jan 27, 2016 at 14:40
  • YES ! Thanks Steven, your method works ! Thanks a lot :) ! Post it so I can mark it as answered.
    – François
    Jan 27, 2016 at 14:55

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.