- """
- 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的美女
- """
Python3.4-文本-替换字符串中的子串
最新推荐文章于 2024-04-30 16:25:42 发布