我在Python中有以下字符串:thestring = "123\n456"
在我的Jinja2模板中,我使用{{thestring}}
,输出为:
123
456
我可以让Jinja2打印确切的代表123\n456
(包括\n
)的唯一方法是逃避thestring = "123\\n456"
。
还有其他方法可以直接在模板中完成吗?
答案 0 :(得分:3)
我会自己回答,也许这对有同样问题的人有帮助。
这有效:{{thestring.encode('string_escape')}}
答案 1 :(得分:0)
对我来说{{thestring.encode('string_escape')}}
失败,并出现以下错误:
escape_encode() argument 1 must be string, not AnsibleUnicode
不确定我做错了什么,但是以下内容对我来说很好:
{{ thestring | replace('\n','\\n') }}