在Python中实现替换字符串中的子串的示例


Posted in Python onOctober 31, 2018

假如有个任务: 给定一个字符串,通过查询字典,来替换给定字符中的变量。如果使用通常的方法:

>>> "This is a %(var)s" % {"var":"dog"}
'This is a dog'
>>>

其实可以使用string.Template类来实现上面的替换

>>> from string import Template
>>> words = Template("This is $var")
>>> print(words.substitute({"var": "dog"})) # 通过字典的方式来传参
This is dog
>>> print(words.substitute(var="dog"))   # 通过关键字方式来传参
This is dog
>>>

在创建Template实例时,在字符串格式中,可以使用两个美元符来代替$,还可以用${}将 变量扩起来,这样的话,变量后面还可以接其他字符或数字,这个使用方式很像Shell或者Perl里面的语言。下面以letter模板来示例一下:

>>> from string import Template
>>> letter = """Dear $customer,
... I hope you are having a great time!
... If you do not find Room $room to your satisfaction, let us know.
... Please accept this $$5 coupon.
...     Sincerely,
...     $manager,
...     ${name}Inn"""
>>> template = Template(letter)
>>> letter_dict = {"name": "Sleepy", "customer": "Fred Smith", "manager": "Tom Smith", "room": 308}
>>> print(template.substitute(letter_dict))
Dear Fred Smith,
I hope you are having a great time!
If you do not find Room 308 to your satisfaction, let us know.
Please accept this $5 coupon.
    Sincerely,
    Tom Smith,
    SleepyInn
>>>

有时候,为了给substitute准备一个字典做参数,最简单的方法是设定一些本地变量,然后将这些变量交给local()(此函数创建一个字典,字典中的key就是本地变量,本地变量的值通过key来访问)。

>>> locals()   # 刚进入时,没有其他变量
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> name = "Alice" # 创建本地变量name 
>>> age = 18   # 创建本地变量age
>>> locals()   # 再执行locals()函数就可以看到name, age的键值队
{'name': 'Alice', '__builtins__': <module '__builtin__' (built-in)>, 'age': 18, '__package__': None, '__name__': '__mai
__', '__doc__': None}
>>> locals()["name"] # 通过键name来获取值
'Alice'
>>> locals()["age"] # 通过键age来获取值
18
>>>

有了上面的例子打底来看一个示例:

>>> from string import Template
>>> msg = Template("The square of $number is $square")
>>> for number in range(10):
...  square = number * number
...  print msg.substitute(locals())
...
The square of 0 is 0
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9

另外一种方法是使用关键字参数语法而非字典,直接将值传递给substitute。

>>> from string import Template
>>> msg = Template("The square of $number is $square")
>>> for i in range(4):
...  print msg.substitute(number=i, square=i*i)
...
The square of 0 is 0
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
>>>

甚至可以同时传递字典和关键字

>>> from string import Template
>>> msg = Template("The square of $number is $square")
>>> for number in range(4):
...  print msg.substitute(locals(), square=number*number)
...
The square of 0 is 0
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
>>>

为了防止字典的条目和关键字参数显示传递的值发生冲突,关键字参数优先,比如:

>>> from string import Template
>>> msg = Template("It is $adj $msg")
>>> adj = "interesting"
>>> print(msg.substitute(locals(), msg="message"))
It is interesting message

以上这篇在Python中实现替换字符串中的子串的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python超简单解决约瑟夫环问题
May 12 Python
利用Python批量生成任意尺寸的图片
Aug 29 Python
Python实现脚本锁功能(同时只能执行一个脚本)
May 10 Python
python实现自动发送邮件发送多人、群发、多附件的示例
Jan 23 Python
python进行文件对比的方法
Dec 24 Python
浅谈PySpark SQL 相关知识介绍
Jun 14 Python
解决pyqt5中QToolButton无法使用的问题
Jun 21 Python
Python flask框架post接口调用示例
Jul 03 Python
Python能做什么
Jun 02 Python
python统计mysql数据量变化并调用接口告警的示例代码
Sep 21 Python
Django实现简单的分页功能
Feb 22 Python
python+pytest接口自动化之token关联登录的实现
Apr 06 Python
python创建文件时去掉非法字符的方法
Oct 31 #Python
python3 中文乱码与默认编码格式设定方法
Oct 31 #Python
解决python中 f.write写入中文出错的问题
Oct 31 #Python
[原创]Python入门教程3. 列表基本操作【定义、运算、常用函数】
Oct 30 #Python
python将txt文件读入为np.array的方法
Oct 30 #Python
Python 将Matrix、Dict保存到文件的方法
Oct 30 #Python
python将字符串以utf-8格式保存在txt文件中的方法
Oct 30 #Python
You might like
深入PHP操作MongoDB的技术总结
2013/06/02 PHP
php数组合并的二种方法
2014/03/21 PHP
PHP实现即时输出、实时输出内容方法
2015/05/27 PHP
PHP利用Mysql锁解决高并发的方法
2018/09/04 PHP
实例介绍PHP删除数组中的重复元素
2019/03/03 PHP
详解PHP 二维数组排序保持键名不变
2019/03/06 PHP
B/S开发中常用javaScript技术与代码
2007/03/09 Javascript
javascript 写类方式之二
2009/07/05 Javascript
json属性名为什么要双引号(个人猜测)
2014/07/31 Javascript
jQuery的context属性用法实例
2014/12/27 Javascript
Javascript 拖拽雏形中的一些问题(逐行分析代码,让你轻松了拖拽的原理)
2015/01/23 Javascript
浅谈如何实现easyui的datebox格式化
2016/06/12 Javascript
jquery中live()方法和bind()方法区别分析
2016/06/23 Javascript
Vue.js学习记录之在元素与template中使用v-if指令实例
2017/06/27 Javascript
在页面中引入js的两种方法(推荐)
2017/08/29 Javascript
利用原生js实现html5小游戏之打砖块(附源码)
2018/01/03 Javascript
JS实现多物体运动的方法详解
2018/01/23 Javascript
JavaScript实现正则去除a标签并保留内容的方法【测试可用】
2018/07/18 Javascript
p5.js临摹动态图形的方法
2019/10/23 Javascript
js实现简单贪吃蛇游戏
2020/05/15 Javascript
jquery实现有过渡效果的tab切换
2020/07/17 jQuery
vue实现多个echarts根据屏幕大小变化而变化实例
2020/07/19 Javascript
JavaScript 监听组合按键思路及代码实现
2020/07/28 Javascript
python机器学习之贝叶斯分类
2018/03/26 Python
利用Python如何实现数据驱动的接口自动化测试
2018/05/11 Python
基于anaconda下强大的conda命令介绍
2018/06/11 Python
Python使用Shelve保存对象方法总结
2019/01/28 Python
OpenCV搞定腾讯滑块验证码的实现代码
2019/05/18 Python
关于python 跨域处理方式详解
2020/03/28 Python
ZINVO手表官网:男士和女士手表
2019/03/10 全球购物
计算机应用职专应届生求职信
2013/11/12 职场文书
电焊工工作岗位职责
2014/02/06 职场文书
社区工作感言
2014/02/21 职场文书
模具专业自荐信
2014/05/29 职场文书
企业财务经理岗位职责
2015/04/08 职场文书
刑事附带民事代理词
2015/05/25 职场文书