-1

I'm trying to make search functionality to output all available books based on author/title or genre typed in a form (I'm using sqlite), using LIKE function.

The piece of code I'm using is as follows:

# User reached route via POST (submitting the form)
else:
    query = request.form.get("query")

    # Ensure query is not blank
    if not query:
        return apology("you haven't typed anything!", 400)

    # Implementing search
    books = db.execute("SELECT author, title, genre, id FROM books WHERE booked = 0 AND (author LIKE '%' || :query || '%' OR title LIKE '%' || :query || '%' OR genre LIKE '%' || :query || '%')",
                      query = query)

However, users often type query followed by a space (especially on mobile devices). And in this case the code doesn't work.

  1. How can I account for the situation with a space after the query and fix this?
  2. Is it possible to account for infinite number of spaces? E.g. if I print 2 spaces after?

Thanks!

davidism
  • 121,510
  • 29
  • 395
  • 339
Sabie
  • 77
  • 1
  • 8
  • 1
    Use strip(): `query = request.form.get("query").strip()` to remove any leading or trailing spaces. – forpas Dec 06 '20 at 11:30

1 Answers1

3

If you don't want white space at either end of the query, you can trim the input:

query = request.form.get("query").strip();

This also makes sure if not query part is executed when the query consists solely of white space.

Cem
  • 1,276
  • 4
  • 17