Python壳新林

2024-04-26 11:46:47 发布

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

我正在阅读一本书中的教程,我对“\n”有一些问题。在

以下是要求我在Python shell中键入的代码:

from django.template import Template, Context

template = Template(
    '{{ ml.exclaim }}!\n'
    'she said {{ ml.adverb }}\n'
    'as she jumped into her convertible {{ ml.noun1 }}\n'
    'and drove off with her {{ ml.noun2 }}.\n'
)

mad_lib = {
    'exclaim':'Ouch',
    'adverb':'dutifully',
    'noun1':'boat',
    'noun2':'pineapple',
}

context = Context({'ml': mad_lib})
template.render(context)

因此,每当我将它输入Python shell时,它会立即返回它:

^{pr2}$

我想把它分成几行:

Ouch!
she said dutifully
as she jumped into her convertible boat
and drove off with her pineapple.

感谢所有的帮助。在


Tags: ascontexttemplateshellmlsheintoconvertible
2条回答

使用autoescape template tag来esacpe HTML换行符(<;br/>;)字符。

另外,由于您没有html linebreak字符,您必须使用linebreaksbrDjango template filter将文本文件换行转换为html linebreaks,如[this][1]答案中建议的那样。

注意:当您尝试直接用html打印时,它会起作用。

在python中,相邻出现的字符串会自动组合在一起,因此

>>> s1 = "hello " "world"
>>> s2 = "hello world"
>>> s3 = "hello"
..."world" \
>>> s1 == s2 == s3
True

呈现的字符串与预期的结果完全一致。 但是,我想你只是在问如何使\n实际上打破了一条线, 只需使用print template.render(context)

相关问题 更多 >