在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 条件判断的缩写方法
Sep 06 Python
Python最基本的输入输出详解
Apr 25 Python
Python学习小技巧总结
Jun 10 Python
Python初学者需要注意的事项小结(python2与python3)
Sep 26 Python
GitHub 热门:Python 算法大全,Star 超过 2 万
Apr 29 Python
python如何以表格形式打印输出的方法示例
Jun 21 Python
python3读取图片并灰度化图片的四种方法(OpenCV、PIL.Image、TensorFlow方法)总结
Jul 04 Python
python读写csv文件方法详细总结
Jul 05 Python
从pandas一个单元格的字符串中提取字符串方式
Dec 17 Python
浅谈Python访问MySQL的正确姿势
Jan 07 Python
PyQt5 QThread倒计时功能的实现代码
Apr 02 Python
python实现简单的井字棋
May 26 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
全国FM电台频率大全 - 14 江西省
2020/03/11 无线电
ThinkPHP单字母函数(快捷方法)使用总结
2014/07/23 PHP
php接口数据加密、解密、验证签名
2015/03/12 PHP
求帮忙修改个php curl模拟post请求内容后并下载文件的解决思路
2015/09/20 PHP
详解PHP的Yii框架的运行机制及其路由功能
2016/03/17 PHP
微信公众平台开发(五) 天气预报功能开发
2016/12/03 PHP
php中文语义分析实现方法示例
2019/09/28 PHP
js option删除代码集合
2008/11/12 Javascript
Javascript学习笔记7 原型链的原理
2010/01/11 Javascript
文本框回车提交与禁止提交示例
2013/09/27 Javascript
jQuery ajax中使用confirm,确认是否删除的简单实例
2016/06/17 Javascript
angularJs关于指令的一些冷门属性详解
2016/10/24 Javascript
详解Vue 实例中的生命周期钩子
2017/03/21 Javascript
微信小程序实现带刻度尺滑块功能
2017/03/29 Javascript
微信小程序 如何引入外部字体库iconfont的图标
2018/01/31 Javascript
axios向后台传递数组作为参数的方法
2018/08/11 Javascript
vue eslint简要配置教程详解
2019/07/26 Javascript
Python实例一个类背后发生了什么
2016/02/09 Python
对python插入数据库和生成插入sql的示例讲解
2018/11/14 Python
python中类与对象之间的关系详解
2020/12/16 Python
python实现学生通讯录管理系统
2021/02/25 Python
手机端用rem+scss做适配的详解
2017/11/15 HTML / CSS
html5调用app分享功能示例(WebViewJavascriptBridge)
2018/03/21 HTML / CSS
为奢侈时尚带来了慈善元素:Olivela
2018/09/29 全球购物
写出程序把一个链表中的接点顺序倒排
2014/04/28 面试题
劳资专员岗位职责
2013/12/27 职场文书
初中考试作弊检讨书
2014/02/01 职场文书
小学生元旦广播稿
2014/02/21 职场文书
《这儿真好》教学反思
2014/02/22 职场文书
个人担保书格式范文
2014/05/12 职场文书
酒店管理专业自荐信
2014/05/23 职场文书
群众路线教育党员自我剖析材料
2014/10/06 职场文书
业务员工作态度散漫检讨书
2014/11/02 职场文书
人才市场接收函
2015/01/30 职场文书
语文教师求职信范文
2015/03/20 职场文书
工商局调档介绍信
2015/10/22 职场文书