如何使用listlike类型生成标记字符串模板Python?

2024-05-19 10:08:39 发布

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

我有以下模板

from string import Template
myTemplate = '''$heading
| Name | Age |
| ---- |---- |
'''

问题是,我不知道在编写模板时,表中会有多少人。所以我想传入一个元组列表,比如:

myTemplate.substitute(...=[("Tom", "23"), ("Bill", "43"), ("Tim", "1")])

如何做到这一点?如果我只是为带有元组的列表添加一个占位符,这将不起作用,因为周围的数据格式将丢失。你知道吗

我希望模板捕获格式,列表捕获数据并保持这两个元素分开。你知道吗

结果如下:

| Name | Age |
| ---- |---- |
| Tom  | 23  |
| Bill | 43  |
| Tim  | 1   |

Tags: namefromimport模板列表agestringtemplate
2条回答

我推荐Mustache。这是一个简单的模板引擎,可以做你需要的。你知道吗

不想导入功能齐全的模板引擎可能是有原因的,比如想在资源严重受限的环境中运行代码。如果是这样的话,用几行代码就不难做到这一点。你知道吗

下面可以处理模板字符串中最多包含26个元素的元组列表,这些元素在模板字符串中标识为$a到$Z,并返回模板扩展列表。你知道吗

from string import Template

def iterate_template( template, items):
   AZ=[ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i:i+1] for i in range(26) ] # ['A','B',... 'Z']
   return [ Template(template).safe_substitute(
       dict(zip( AZ, elem ))) for elem in items ]

编辑:为了提高效率,我应该实例化一次模板,并在列表中多次使用它:

def iterate_template( template, items):
   AZ=[ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i:i+1] for i in range(26) ] # ['A','B',... 'Z']
   tem = Template(template)
   return [ tem.safe_substitute( dict(zip( AZ, elem ))) for elem in items ]

使用示例

>>> table = [('cats','feline'), ('dogs','canine')]

>>> iterate_template('| $A | $B |', table )
['| cats | feline |', '| dogs | canine |']

>>> x=Template('$heading\n$stuff').substitute( 
      heading='This is a title',
      stuff='\n'.join(iterate_template('| $A | $B | $C |', 
         [('cats','feline'),   ('dogs', 'canine', 'pack')] ) ) # slight oops
  )
>>> print(x)
This is a title
| cats | feline | $C |
| dogs | canine | pack |

相关问题 更多 >

    热门问题