python-Template(模板字符串)

本文介绍了Python的string模块中的Template类,用于创建模板字符串。Template使用$作为标识符,支持通过substitute和safe_substitute方法进行参数替换。substitute在参数缺失时会抛出错误,而safe_substitute则会保留未替换的占位符。示例中展示了如何实例化Template对象,以及两种方法的使用和区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python-Template(模板字符串)

一、导入

这个类位于string模块下

from string import Template

二、要先实例化对象,实例化的时候要传入字符串

​ 1、

template = Template("今晚打老虎, 我喜欢头发长,身材好,屁股白,腿细,胸大的年轻漂亮女孩!")

2、Template以$为特殊标识符,它具有以下规则:

  • 它的主要实现方式为$xxx,其中xxx是满足python命名规则的字符串,即不能以数字,不能为关键字
  • 如果xxx需要和其他字符串接触时,可以将xxx包裹起来,例如xxx需要和其他字符串接触时,可以{}将xxx包裹起来, 例如xxx需要和其他字符串接触时,可以xxx包裹起来,例如{aaa}aaa

3、Template中有两个重要的方法:substitute和safe_substitute

​ 这两个方法都可以通过获取参数返回字符串

template = Template("There $a and $b")
result = template.substitute(a="apple", b="orange")
print(result)    # substitute

还可以通过字典直接传递数据:

template = Template("There $a and $b")
result = template.substitute({"a": "apple", "b": "orange"})
print(result)    # safe_substitute

区别在于参数缺少时的处理方式:

substitute:如果少穿参数或者参数传递的错误会直接报错

template = Template("There $a and $b")
result = template.substitute(a="apple")  
print(result)    # KeyError: 'b'

safe_substitute:如果少传参数或者传递的参数错误,并不会报错,并且会将原始占位符将完整显示在结果字符串中。

template = Template("There $a and $b")
result = template.safe_substitute({"a": "apple"})
print(result)    # There apple and $b
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值