> ## Content Index
> Fetch the complete content index at: https://yinguobing.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# 使用Python Template格式化拼接长字符串
- URL: https://yinguobing.com/blog/shi-yong-python-templatege-shi-hua-logzi-fu-chuan/
- Published: 2021-08-13T14:01:03.000Z
- Updated: 2021-08-13T14:01:03.000Z
- Description: 高效格式化多项目拼接成的字符串，打log必备。
- Author: 尹国冰
- Tags: Python

项目中有时候会遇到由多个项目组合而成的长字符串输出场景。例如某商超系统中录入的两条产品信息：

```python
商品名：电饭煲
品牌：苏泊尔
价格：299
促销价格：199

商品名：无线路由器
品牌：小米
价格：599
促销价格：99

```

如果使用常规的 `print` 方法打印出来大概是这个样子：

```bash
商品名:电饭煲 品牌:苏泊尔 价格:299 促销价格:199
商品名:无线路由器 品牌:小米 价格:599 促销价格:99
```

当有大量的输出需要检视时，我们会希望这些输出能够像表格一样对齐。典型的做法是使用python字符串的 `format` 方法。例如：

```python
print("商品名:{:<5s} 品牌:{:<5s} 价格:{:5d} 促销价格:{:5d}".format('电饭煲','苏泊尔',299, 199))
```

其中商品名与品牌为字符串，左对齐；价格与促销价格为整型数，右对齐。输出结果大概是这样：

```bash
商品名:电饭煲        品牌:苏泊尔    价格: 299 促销价格: 199
商品名:无线路由器    品牌:小米     价格: 599 促销价格:  99
```

但是当拼接的项目太多的时候，这么写起来就很累了。尤其是面对多个输出行时，一旦要更改需要重复劳动。

这时候可以考虑使用Python string模块的Template。

```python
from string import Template
t = Template("商品名:$name 品牌:$brand 价格:$price 促销价格:$discount")
s = t.substitute(name="{:<8s}".format("电饭煲"), 
                 brand="{:<8s}".format("苏泊尔"), 
                 price="{:4d}".format(299), 
                 discount="{:4d}".format(199))
print(s)
------------------
商品名:电饭煲      品牌:苏泊尔      价格: 299 促销价格: 199
```

这么做增加了代码行数，但是实现了项目顺序与项目格式及内容的分离。当字符串中涉及到的拼接项目数量增多，调整顺序或者格式时可以最大限度的避免混乱。