在python中使用jinja2连接字符串和数字

2024-05-15 19:30:21 发布

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

To concatenate strings and numbers in my python script ,now I use string.format() as follows ,How can I use jinja2 for the same.

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来格式化字符串,我该怎么做呢。提前谢谢。


Tags: toinformatjinja2foragegetif
2条回答

来自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'))

开/关

abc;25;abc@gmail.com

xyz

你可以这样做:

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

这是因为在Jinja2中,如果有未定义的内容,Jinja2将插入“nothing”。

我利用自由忽略了你的空间分配。如果需要空格,那么可以使用Jinja2的if-expressions

{{ "%s ;" % item['email'] if item['email'] is defined else ";" }}

相关问题 更多 >