以有序结构呈现列表,不带unicode字符

2024-09-29 20:26:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表如下:

[(u'Element1', u'Description1', u'Status1), (u'newElement2', u'newDescription2', u'newStatus2), (u'nextElement3', u'nextDescription3', u'nextStatus3), (u'anotherElement4', u'anotherDescription4', u'anotherStatus4)] 

我有一个ansible playbook,它使用jinja2模板将列表呈现为文本文件。模板文件如下所示:

{% for item in description | batch(3, ' ') %}
{% for el in item %}
{{ el }}
{% endfor %}
{% endfor %}

但返回的文本文件如下所示:

[u'Element1', u'Description1', u'Status1]
[u'newElement2', u'newDescription2', u'newStatus2]
[u'nextElement3', u'nextDescription3', u'nextStatus3]
[u'anotherElement4', u'anotherDescription4', u'anotherStatus4]

我希望报告是这样的:

Element1           Description1           Status1
newElement2        nextDescription2       newStatus2
nextElement3       nextDescription3       nextStatus3
anotherElement4    anotherDescription4    anotherDescription4

有没有办法删除unicode字符并以这种方式呈现列表?你知道吗


Tags: 模板列表文本文件element1description1status1newelement2anotherstatus4
2条回答

例如:

{% for row in description %}
{% for cell in row %}
{{ "%-22s"|format(cell) }} 
{%- endfor %}

{% endfor %}

收益率:

Element1              Description1          Status1
newElement2           newDescription2       newStatus2
nextElement3          nextDescription3      nextStatus3
anotherElement4       anotherDescription4   anotherStatus4

但要获得动态填充(取决于列中元素的最大长度)看起来要复杂得多:{{ "%-22s"|format(cell) }}可以替换为{{ "{0}".format(cell).ljust(width) }},其中width可以是一个变量,但可能需要另一个循环首先收集长度。你知道吗

你可以试试

{% for el in item %}
    {% for e in el %}
        {{ e }}
    {% endfor %}
{% endfor %}

或者使用html表格,如果你想改变格式

相关问题 更多 >

    热门问题