Python3.4-文本-替换字符串中的子串

"""
python版本: 3.4
替换字符串中的子串
"""
import string

info = """姓名: $name,
年龄: $age,
博客: $blog,
http://${weibo},
$$帅
"""
#string.Template(template)
info_template = string.Template(info)

#以字典的方式一一赋值
info_dic={'name':'毕小朋','age':30,'blog':'http://blog.csdn.net/wirelessqa','weibo':"www.weibo.com/wirelessqa"}

#substitute(mapping, **kwds)
print(info_template.substitute(info_dic))
"""
>>
姓名: 毕小朋,
年龄: 30,
博客: http://blog.csdn.net/wirelessqa,
http://www.weibo.com,
$帅
"""

#转成字典后再赋值
info_dic2=dict(name='毕小朋',age=30,blog='http://blog.csdn.net/wirelessqa',weibo='www.weibo.com/wirelessqa')

print(info_template.substitute(info_dic2))
"""
>>
姓名: 毕小朋,
年龄: 30,
博客: http://blog.csdn.net/wirelessqa,
http://www.weibo.com,
$帅
"""

#safe_substitute(mapping, **kwds)
#当我们少一个键(weibo被拿掉了哦)时,查看结果如何
test_safe_substitute=dict(name='毕小朋',age=30,blog='http://blog.csdn.net/wirelessqa')

try:
	print(info_template.substitute(test_safe_substitute))
except KeyError:
	print("error: 映射中没有weibo这个键")

"""
>>
error: 映射中没有weibo这个键
"""
#使用safe_substitute(mapping, **kwds)
print(info_template.safe_substitute(test_safe_substitute))
"""
>>
姓名: 毕小朋,
年龄: 30,
博客: http://blog.csdn.net/wirelessqa,
http://${weibo},
$帅
"""

#locals()提供了基于字典的访问局部变量的方式
info = string.Template('老毕是$shuai,芳龄$age')
shuai='帅哥'
age=18
print(info.substitute(locals())) #>>老毕是帅哥,芳龄18

#使用关键字作为参数替换
info = string.Template('老毕喜欢年龄$age的$who')
for i in range(18,39):
	print(info.substitute(age=i,who='美女'))

"""
>>
老毕喜欢年龄18的美女
老毕喜欢年龄19的美女
老毕喜欢年龄20的美女
老毕喜欢年龄21的美女
....
老毕喜欢年龄38的美女
"""

#同时使用关键字参数和字典
for age in range(18,39):
	print(info.substitute(locals(),who='美女'))
"""
>>
老毕喜欢年龄18的美女
老毕喜欢年龄19的美女
老毕喜欢年龄20的美女
老毕喜欢年龄21的美女
....
老毕喜欢年龄38的美女
"""

订阅

微信搜索“毕小烦”或者扫描下面的二维码,即可订阅我的文章。

image.png

如果文章对你有帮助,请随手点个赞吧!

(完)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

毕小烦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值