Search code examples
pythonstringjinja2

Jinja2/Python - Strings to Integers for comparison


I have strings like the following:

Team Li vs. Team Aguilar || SCORE (W-L-T): 5-4-0     
Favors Flavors vs. Cupcakes For Breakfast || SCORE (W-L-T): 11-2-1

I would like the text to be green if the "W" value is greater than the "L" value, and red if the "L" value is greater than the "W" value. I have the following code in Jinja2 that works for the first case, but does not work for the second case. It incorrectly displays the string as red, even though the "W" column is greater than the L column.

{% for item in matchups %}
    {% if (item[-5]|int) > (item[-3]|int) %}
        <font color='green'>{{ item }}</font>
    {% elif (item[-5]|int) == (item[-3]|int) %}
        {{ item }}
    {% else %}
        <font color='red'>{{ item }}</font>
    {% endif %}
     <br>
{% endfor %}

I understand that my code fails because the second string has 2 digits. Is there a good way to fix this issue?

This is a Jinja2 problem, so answers in Jinja2 would be great. However, a Python solution might also work too.


Solution

  • You can extract the elements with two splits (using variables for clarity):

    • first to get the last column (split by whitespace) element:

      {% set results = item.split()[-1] %}
      
    • then to get the first and second of the results (split by the dash):

      {% set w = results.split('-')[0]|int %}
      {% set l = results.split('-')[1]|int %}
      

    The full code (also with a condition to process only lines containing SCORE to handle the one from your now-edited-out example with *************):

    {% for item in matchups %}
      {% if 'SCORE' in item %}
        {% set results = item.split()[-1] %}
        {% set w = results.split('-')[0]|int %}
        {% set l = results.split('-')[1]|int %}
        {% if w > l %}
          <font color='green'>{{ item }}</font>
        {% elif w == l %}
          {{ item }}
        {% else %}
          <font color='red'>{{ item }}</font>
        {% endif %}
        <br>
      {% endif %}
    {% endfor %}