sunnyiitkgp sunnyiitkgp - 5 months ago 35
Python Question

Check if a string starts with any letter between 'A' and 'G' in django template

How can I check if a string starts with 'A' or 'B' or 'C'.... or 'G' in django template.

I've this method presently. Can it be done in a better way?

{% if val|slice:":1" == 'A' or val|slice:":1" == 'B' or val|slice:":1" == 'C'.... or val|slice:":1" == 'G' %}

Answer

Strings are treated like sequences in Python so you can check membership like so:

{% if val|first in 'ABCG' %}
    # Do stuff
{% endif %}