1

Is it possible using Python to select all features whose attribute contain a specific string?

I am new to QGIS.

The layer has an address column ("Bauvorha_3") which looks like this:

Berlin, Am Alexanderplatz, ...

Berlin, Goethestrasse, ...

Hamburg, Alsterufer, ...

Hamburg, Reeperbahn, ...

I need to select all features containing for example "Hamburg" or "ufer".

place is the user-input string. I've tried to use LIKE but it doesn't seem to work for me.

place = self.dlg.lineEdit.text()
place = str(place)
versuch = "'{}'".format(place)
search = '"Bauvorha_3" LIKE "{}%"'.format(versuch)
self.iface.activeLayer().selectByExpression(search)
4
  • 1
    Have you seen this topic Selecting features using an expression with PyQGIS?
    – Taras
    Apr 15, 2020 at 13:05
  • 3
    Try: search = """"Bauvorha_3" LIKE('%{0}%')""".format(place)
    – BERA
    Apr 15, 2020 at 13:51
  • 1
    it worked, thanks a lot @BERA !
    – Brian
    Apr 16, 2020 at 9:20
  • 2
    Then accept my answer with the checkbox
    – BERA
    May 24, 2020 at 18:46

1 Answer 1

1

Try:

search = """"Bauvorha_3" LIKE('%{0}%')""".format(place)

You were missing enclosing () and % sign before keyword. And i f you have alot of single and double quotes inside a string, enclosing everything in three double quotes usually work to make python understand what you want.

1
  • 2
    search = f""""Bauvorha_3" LIKE('%{place}%')"""
    – Jakob
    Apr 16, 2020 at 9:47

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.