0

I have this code

query = request.GET.get("q")
    if query:
        if query == "song" or query == "songs":
            return render(request, 'music/cloud.html', {
                'songs': song_results,
                'generic_songs': song_results_generic,
            })

The thing is, I want the "if" statement to ignor uppercases. For example, when the user search by "SoNg" or "SonG" or.. it will be converted to "song" before testing

2 Answers2

2

Use .lower()

if query.lower() in ['song', 'songs']:
kloddant
  • 840
  • 5
  • 15
1

In Python3.3+, you should prefer str.casefold .

if query.casefold() in ['song'.casefold(), 'songs'.casefold()]:

From the docs:

Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".

The casefolding algorithm is described in section 3.13 of the Unicode Standard.

Community
  • 1
  • 1
Adam Smith
  • 45,072
  • 8
  • 62
  • 94