如何使用 .join() 使用 python 函数中的 '\n' 修复换行符不起作用

How to fix line breaks not working using '\n' from python function with .join()

我有一个函数,当调用它时,它会循环遍历包含评论的字典对象,然后应该显示每个评论并用一行分隔。

我搜索了与此相关的其他主题,但没有找到适合我的答案。

我试过'\n' '',但总是把文字放在一起。

def get_comment(stand):
    ''' Takes a comment code from the each of the comments
    field from inside the stand data and outputs
    a human readable text comment '''
    for _i in range(8):
        if stand:
            for _ in range(len(stand)):
                comments = []
                for _key, codes in stand.items():
                    comment = codes['carrier'] + ':' + \
                    codes['number'] + ' - ' + \
                    SamCode.objects.get(code=codes['dockingCode']).comment
                    comments.append(comment)

            return '\n'.join(comments)

这输出

例如

AA:2776 - Manual start of system - ground AA:335 - Manual start of system - ground

而我需要成为

AA:2776 - Manual start of system - ground

AA:335 - Manual start of system - ground

为 Django 集成添加 html 模板代码。 Column.13 可以有一条或多条评论,Column.14 也一样。取决于评论的来源。

   {% for column in performance.dailyDetails %}
    <td>{{ column.0 }}</td>
    <td>{{ column.1 }}</td>
    <td>{{ column.2 }}</td>
    <td>{{ column.3 }}</td>
    <td>{{ column.4 }}</td>
    <td>{{ column.5 }}</td>
    <td>{{ column.6 }}</td>
    <td>{{ column.7 }}</td>
    <td>{{ column.8 }}</td>
    <td>{{ column.9 }}</td>
    <td>{{ column.10 }}</td>
    <td>{{ column.11 }}</td>
    <td>{{ column.12 }}</td>
    <td>{% if column.13 == None %}
        {% else %}
          {{ column.13 }}<br>
        {% endif %}
        {% if column.14 == None %}
        {% else %}
          {{ column.14 }}<br>
        {% endif %}</td>

这是正在循环的 JSON 词典之一。 IT已经在注释中显示了\n,但是输出到HTML:

时不是换行
{'partition': 'AA',
 'date': '04/14/2019',
 'sortingName': 'ORD.H16', 
 'stand': 'ORD.H16', 
 'acType': 'A321,A321/2,B737/8-WL', 
 'inbound': 7, 
 'outbound': 2, 
 'blockIn': 4, 
 'blockOff': 2, 
 'slaInbound': 4, 
 'slaOutbound': 2, 
 'samInternal': None, 
 'sdkTechnical': None, 
 'ground': 'AA:2776 - Manual start of system - ground\nAA:335 - Manual start of system - ground', 
 'pilot': 'AA:362 - UNK - pilot', 
 'tower': None, 
 'operational': None, 
 'infrastructure': None, 
 'interface': None}

确保评论列表中的所有元素都是字符串对象。

关于您关于在评论之间添加换行符的问题,您几乎答对了。如果你打印函数的返回值,你会得到正确的输出

例如:

>>> x= '\n'.join(['1','2','3'])
>>> x
'1\n2\n3'
>>> print (x)
1
2
3

这完全是输出的问题。 HTML 忽略白色 space,包括换行符;如果你想让数据出现在多行你需要使用 HTML 换行元素,例如 <br>.

有一个 Django 模板过滤器可以将换行符转换为 HTML 中断:linebreaksbr.

{{ column.13|linebreaksbr }}