在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设置socket代理的方法
Jan 14 Python
用Python实现通过哈希算法检测图片重复的教程
Apr 02 Python
在Python的框架中为MySQL实现restful接口的教程
Apr 08 Python
python3实现ftp服务功能(客户端)
Mar 24 Python
Python设计模式之备忘录模式原理与用法详解
Jan 15 Python
浅析Python+OpenCV使用摄像头追踪人脸面部血液变化实现脉搏评估
Oct 17 Python
Django 实现xadmin后台菜单改为中文
Nov 15 Python
利用OpenCV和Python实现查找图片差异
Dec 19 Python
python打印异常信息的两种实现方式
Dec 24 Python
tensorflow mnist 数据加载实现并画图效果
Feb 05 Python
python中format函数如何使用
Jun 22 Python
python中Array和DataFrame相互转换的实例讲解
Feb 03 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
Google Voice 短信发送接口PHP开源版(2010.5更新)
2010/07/22 PHP
PHP 循环删除无限分类子节点的实现代码
2013/06/21 PHP
PHP延迟静态绑定示例分享
2014/06/22 PHP
php计算两个文件相对路径的方法
2015/03/14 PHP
Yii CDBCriteria常用方法实例小结
2017/01/19 PHP
PHP大文件切割上传并带进度条功能示例
2019/07/01 PHP
goto语法在PHP中的使用教程
2020/09/17 PHP
js中字符替换函数String.replace()使用技巧
2011/08/14 Javascript
jquery实现效果比较好的table选中行颜色
2014/03/25 Javascript
在Mac OS下使用Node.js的简单教程
2015/06/24 Javascript
ES6通过babel转码使用webpack使用import关键字
2016/12/13 Javascript
利用JS实现简单的日期选择插件
2017/01/23 Javascript
jQuery.extend 与 jQuery.fn.extend的用法及区别实例分析
2018/07/25 jQuery
js实现轮播图的完整代码
2020/10/26 Javascript
Angular6新特性之Angular Material
2018/12/28 Javascript
微信小程序登录态和检验注册过没的app.js写法
2019/05/22 Javascript
JS跨浏览器解析XML应用过程详解
2020/10/16 Javascript
vue使用exif获取图片经纬度的示例代码
2020/12/11 Vue.js
对Python 2.7 pandas 中的read_excel详解
2018/05/04 Python
PyCharm的设置方法和第一个Python程序的建立
2019/01/16 Python
Django如何自定义model创建数据库索引的顺序
2019/06/20 Python
python pytest进阶之conftest.py详解
2019/06/27 Python
django多种支付、并发订单处理实例代码
2019/12/13 Python
新建文件时Pycharm中自动设置头部模板信息的方法
2020/04/17 Python
使用css实现android系统的loading加载动画
2019/07/25 HTML / CSS
英国领先的在线高尔夫商店:Scottsdale Golf
2019/08/26 全球购物
开办加工厂创业计划书
2014/01/03 职场文书
关于运动会的稿件
2014/02/02 职场文书
《歌唱二小放牛郎》教学反思
2014/04/19 职场文书
单位授权委托书范文
2014/08/02 职场文书
爱的奉献演讲稿
2014/09/10 职场文书
医院见习报告范文
2014/11/03 职场文书
西岭雪山导游词
2015/02/06 职场文书
2015年度学校应急管理工作总结
2015/10/22 职场文书
解决MySQL存储时间出现不一致的问题
2021/04/28 MySQL
html中显示特殊符号(附带特殊字符对应表)
2021/06/21 HTML / CSS