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

  1. """ 
  2. python版本: 3.4 
  3. 替换字符串中的子串 
  4. """  
  5. import string  
  6.   
  7. info = """姓名: $name, 
  8. 年龄: $age, 
  9. 博客: $blog, 
  10. http://${weibo}, 
  11. $$帅 
  12. """  
  13. #string.Template(template)  
  14. info_template = string.Template(info)  
  15.   
  16. #以字典的方式一一赋值  
  17. info_dic={'name':'毕小朋','age':30,'blog':'http://blog.csdn.net/wirelessqa','weibo':"www.weibo.com/wirelessqa"}  
  18.   
  19. #substitute(mapping, **kwds)  
  20. print(info_template.substitute(info_dic))  
  21. """ 
  22. >> 
  23. 姓名: 毕小朋, 
  24. 年龄: 30, 
  25. 博客: http://blog.csdn.net/wirelessqa, 
  26. http://www.weibo.com, 
  27. $帅 
  28. """  
  29.   
  30. #转成字典后再赋值  
  31. info_dic2=dict(name='毕小朋',age=30,blog='http://blog.csdn.net/wirelessqa',weibo='www.weibo.com/wirelessqa')  
  32.   
  33. print(info_template.substitute(info_dic2))  
  34. """ 
  35. >> 
  36. 姓名: 毕小朋, 
  37. 年龄: 30, 
  38. 博客: http://blog.csdn.net/wirelessqa, 
  39. http://www.weibo.com, 
  40. $帅 
  41. """  
  42.   
  43. #safe_substitute(mapping, **kwds)  
  44. #当我们少一个键(weibo被拿掉了哦)时,查看结果如何  
  45. test_safe_substitute=dict(name='毕小朋',age=30,blog='http://blog.csdn.net/wirelessqa')  
  46.   
  47. try:  
  48.     print(info_template.substitute(test_safe_substitute))  
  49. except KeyError:  
  50.     print("error: 映射中没有weibo这个键")  
  51.   
  52. """ 
  53. >> 
  54. error: 映射中没有weibo这个键 
  55. """  
  56. #使用safe_substitute(mapping, **kwds)  
  57. print(info_template.safe_substitute(test_safe_substitute))  
  58. """ 
  59. >> 
  60. 姓名: 毕小朋, 
  61. 年龄: 30, 
  62. 博客: http://blog.csdn.net/wirelessqa, 
  63. http://${weibo}, 
  64. $帅 
  65. """  
  66.   
  67. #locals()提供了基于字典的访问局部变量的方式  
  68. info = string.Template('老毕是$shuai,芳龄$age')  
  69. shuai='帅哥'  
  70. age=18  
  71. print(info.substitute(locals())) #>>老毕是帅哥,芳龄18  
  72.   
  73. #使用关键字作为参数替换  
  74. info = string.Template('老毕喜欢年龄$age的$who')  
  75. for i in range(18,39):  
  76.     print(info.substitute(age=i,who='美女'))  
  77.   
  78. """ 
  79. >> 
  80. 老毕喜欢年龄18的美女 
  81. 老毕喜欢年龄19的美女 
  82. 老毕喜欢年龄20的美女 
  83. 老毕喜欢年龄21的美女 
  84. .... 
  85. 老毕喜欢年龄38的美女 
  86. """  
  87.   
  88. #同时使用关键字参数和字典  
  89. for age in range(18,39):  
  90.     print(info.substitute(locals(),who='美女'))  
  91. """ 
  92. >> 
  93. 老毕喜欢年龄18的美女 
  94. 老毕喜欢年龄19的美女 
  95. 老毕喜欢年龄20的美女 
  96. 老毕喜欢年龄21的美女 
  97. .... 
  98. 老毕喜欢年龄38的美女 
  99. """  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值