1

为了在我的 python 脚本中连接字符串和数字,现在我使用 string.format() 如下,我如何使用 jinja2 来做同样的事情。

for item in mylist:
        mystr = '{}{}{}'.format(item['name'] + ' ;' + 
                ' ' + str(item['age'])+ ' ;'  if item.get('age') else ';',
                ' ' + item['email']+ ' ;' if item.get('email') else ';'                        
                )

mystr 的一些示例输出是

 1. abc ; 25 ; abc@gmail.com
 2. cdf ;;;

我想在我的 python 脚本中使用 jinja2 来格式化字符串。我该怎么做。提前致谢。

4

2 回答 2

3

你可以这样做:

{{ item['name'] }};{{ item['age'] }};{{ item['email'] }};

这是因为在 Jinja2 中,如果某些内容未定义,Jinja2 将插入“无”。

我随意忽略了您的空间分布。如果你需要空格,那么你可以使用 Jinja2 的if-expressions

{{ "%s ;" % item['email'] if item['email'] is defined else ";" }}
于 2013-07-24T11:40:57.840 回答
1

从 jinja2 导入模板

template = Template(
            "{{ name }} ;"
            "{{ ' 'if age }}{{age if age }}{{' 'if age}};"
            "{{ ' ' if email}};{{ email if email}}{{ ' ' if email}};")

for item in mylist:
    people_tag =template.render(
                    name= item['name'],
                    age = item.get('age'),
                    email= item.get('email'))

o/p

ABC; 25; abc@gmail.com;

xyz;;;

于 2013-07-25T11:14:02.773 回答