2016-11-15 25 views
1

我正在關注一本書中的教程,並且遇到了有關「\ n」的一些問題。Python shell - 新行

這裏是我被要求輸入在Python殼代碼:

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中,談到回報它,因爲這一切在一次:

u'Ouch!\nshe said dutifully\nas she jumped into her convertible boat\nand drove off with her pineapple.\n' 

我想擁有它出來像這樣所有在單獨的行:

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

所有幫助表示讚賞。

+0

'打印template.render(上下文)' – ForceBru

+0

模板採取HTML,所以你可以放心地使用''
,而不是'\ N' – karthikr

+0

沒有涉及到HTML,爲什麼每個人都回答有關
ospider

回答

0

字符串出現彼此相鄰的蟒蛇被自動組合在一起,所以

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

渲染的字符串是你應該期望確切的結果。 但是,我認爲你只是問如何讓\n實際上打破了線, 只需使用print template.render(context)

0

使用autoescape template tag到esacpe HTML換行符(< BR />)字符。

此外,因爲你沒有做HTML字符linebreak,你要轉換的文本文件換行符爲HTML linebreaks,使用linebreaksbrDjango template filte R,如[這裏] [1]的答案建議。

注意: - 它會工作,當你嘗試直接在html中打印。