Jinja2 / Python - 用于比较的字符串

时间:2016-12-22 07:31:46

标签: python string jinja2

我有以下字符串:

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

如果“W”值大于“L”值,我希望文本为绿色;如果“L”值大于“W”值,我希望文本为红色。我在Jinja2中有以下代码适用于第一种情况,但不适用于第二种情况。它错误地将字符串显示为红色,即使“W”列大于L列。

{% 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 %}

我理解我的代码失败了,因为第二个字符串有2位数。有没有一种解决这个问题的好方法?

这是一个Jinja2问题,因此Jinja2中的答案会很棒。但是,Python解决方案也可能有用。

1 个答案:

答案 0 :(得分:1)

您可以使用两个拆分提取元素(为清晰起见,使用变量):

  • 首先获取最后一列(由空格分割)元素:

    {% set results = item.split()[-1] %}
    
  • 然后得到第一个和第二个结果(用破折号分开):

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

完整代码(还包含一个条件,只处理包含SCORE的行来处理您现在已编辑的*************示例中的行:

{% 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 %}