Python3.4-文本-替换字符串中的子串
2014-04-23 23:03
513 查看
""" 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-文本-替换字符串中的子串
- python替换字符串中的子串 %(xxxx)s
- python3.4学习笔记(十五) 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- 【python cookbook】替换字符串中的子串(使用Template)
- 如何用Python来进行查询和替换一个文本字符串
- 如何用Python来进行查询和替换一个文本字符串?
- python替换字符串中的子串 %(xxxx)s
- 001_016 Python 替换字符串中的子串
- 001_017 Python 替换字符串中的子串string.template
- 【python cookbook】 替换字符串中的子串
- 《Python CookBook2》 第一章 文本 - 替换字符串中的子串
- Python正则表达式如何进行字符串替换
- 轻松python文本专题-单独处理字符串每个字符的方法汇总
- 黄聪:Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- 轻松python文本专题-判断对象里面是否是类字符串(推荐使用isinstance(obj,str))
- 基于《PythonCookbook》的学习(2)——在字符串的卡头或结尾做文本匹配
- python3.4学习笔记(二十一) python实现指定字符串补全空格、前面填充0的方法
- 轻松python文本专题-字符串开头或者结尾匹配
- python 字符串替换
- python 字符串替换