在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之eval()函数危险性浅析
Jul 03 Python
Python获取Windows或Linux主机名称通用函数分享
Nov 22 Python
Python开发常用的一些开源Package分享
Feb 14 Python
使用基于Python的Tornado框架的HTTP客户端的教程
Apr 24 Python
详解Python中的条件判断语句
May 14 Python
python程序中的线程操作 concurrent模块使用详解
Sep 23 Python
python 实现将list转成字符串,中间用空格隔开
Dec 25 Python
python代码能做成软件吗
Jul 24 Python
matplotlib 多个图像共用一个colorbar的实现示例
Sep 10 Python
Python+unittest+DDT实现数据驱动测试
Nov 30 Python
python脚本使用阿里云slb对恶意攻击进行封堵的实现
Feb 04 Python
Python提取PDF指定内容并生成新文件
Jun 09 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
解析将多维数组转换为支持curl提交的一维数组格式
2013/07/08 PHP
Yii CDBCriteria常用方法实例小结
2017/01/19 PHP
JS中==与===操作符的比较
2009/03/21 Javascript
基于JavaScript实现继承机制之原型链(prototype chaining)的详解
2013/05/07 Javascript
javascript抖动元素的小例子
2013/10/28 Javascript
js 获取、清空input type=&quot;file&quot;的值(示例代码)
2013/12/24 Javascript
JavaScript保留两位小数的2个自定义函数
2014/05/05 Javascript
JS+CSS实现可拖拽的漂亮圆角特效弹出层完整实例
2015/02/13 Javascript
node-webkit打包成exe文件被360误报木马的解决方法
2015/03/11 Javascript
学习使用AngularJS文件上传控件
2016/02/16 Javascript
JavaScript原生编写《飞机大战坦克》游戏完整实例
2017/01/04 Javascript
十大 Node.js 的 Web 框架(快速提升工作效率)
2017/06/30 Javascript
详解VueRouter进阶之导航钩子和路由元信息
2017/09/13 Javascript
JS实现点击li标签弹出对应的索引功能【案例】
2019/02/18 Javascript
基于Taro的微信小程序模板消息-获取formId功能模块封装实践
2019/07/15 Javascript
JavaScript字符串处理常见操作方法小结
2019/11/15 Javascript
JavaScript 几种循环方式以及模块化的总结
2020/09/03 Javascript
[47:42]Fnatic vs Liquid 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
pandas去重复行并分类汇总的实现方法
2019/01/29 Python
使用python搭建服务器并实现Android端与之通信的方法
2019/06/28 Python
什么是python的id函数
2020/06/11 Python
基于Tensorflow的MNIST手写数字识别分类
2020/06/17 Python
Python 如何操作 SQLite 数据库
2020/08/17 Python
工作失误检讨书范文大全
2014/01/13 职场文书
《尊严》教学反思
2014/02/11 职场文书
创业者迈进成功第一步:如何写创业计划书?
2014/03/22 职场文书
二手房购房意向书范本
2014/04/01 职场文书
2015年节能减排工作总结
2015/05/14 职场文书
培训班开班主持词
2015/07/02 职场文书
大学新生入学感想
2015/08/07 职场文书
英语教学课后反思
2016/02/15 职场文书
导游词之永济鹳雀楼
2020/01/16 职场文书
超级详细实用的pycharm常用快捷键
2021/05/12 Python
一劳永逸彻底解决pip install慢的办法
2021/05/24 Python
如何搭建 MySQL 高可用高性能集群
2021/06/21 MySQL
手写实现JS中的new
2021/11/07 Javascript