在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 相关文章推荐
MySQLdb ImportError: libmysqlclient.so.18解决方法
Aug 21 Python
Python实现设置windows桌面壁纸代码分享
Mar 28 Python
Python2.7简单连接与操作MySQL的方法
Apr 27 Python
Python判断列表是否已排序的各种方法及其性能分析
Jun 20 Python
30秒轻松实现TensorFlow物体检测
Mar 14 Python
Python3.x爬虫下载网页图片的实例讲解
May 22 Python
Pycharm以root权限运行脚本的方法
Jan 19 Python
python PIL/cv2/base64相互转换实例
Jan 09 Python
在pytorch 中计算精度、回归率、F1 score等指标的实例
Jan 18 Python
Python列表操作方法详解
Feb 09 Python
详解anaconda离线安装pytorchGPU版
Sep 08 Python
python 批量将中文名转换为拼音
Feb 07 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
上海永华YH-R296(华普R-96)12波段立体声收音机的分析和打理
2021/03/02 无线电
Oracle Faq(Oracle的版本)
2006/10/09 PHP
用PHP产生动态的影像图
2006/10/09 PHP
PHP后台微信支付和支付宝支付开发
2017/04/28 PHP
从jquery的过滤器.filter()方法想到的
2013/09/29 Javascript
探讨jQuery的ajax使用场景(c#)
2013/12/03 Javascript
jQuery实现首页图片淡入淡出效果的方法
2015/06/10 Javascript
JavaScript实现自动生成网页元素功能(按钮、文本等)
2015/11/21 Javascript
AngularJS使用ngMessages进行表单验证
2015/12/27 Javascript
纯js代码制作的网页时钟特效【附实例】
2016/03/30 Javascript
微信小程序使用第三方库Underscore.js步骤详解
2016/09/27 Javascript
AngularJS操作键值对象类似java的hashmap(填坑小结)
2016/11/12 Javascript
jQuery联动日历的实例解析
2016/12/02 Javascript
详解从Node.js的child_process模块来学习父子进程之间的通信
2017/03/27 Javascript
从零开始封装自己的自定义Vue组件
2018/10/09 Javascript
vue+VeeValidate 校验范围实例详解(部分校验,全部校验)
2018/10/19 Javascript
vue项目前端埋点的实现
2019/03/06 Javascript
JS原型与继承操作示例
2019/05/09 Javascript
使用easyui从servlet传递json数据到前端页面的两种方法
2019/09/05 Javascript
JavaScript实现单图片上传并预览功能
2019/09/30 Javascript
[01:48:04]DOTA2-DPC中国联赛 正赛 PSG.LGD vs Elephant BO3 第一场 2月7日
2021/03/11 DOTA
Python 遍历列表里面序号和值的方法(三种)
2017/02/17 Python
python中字符串比较使用is、==和cmp()总结
2018/03/18 Python
python写日志文件操作类与应用示例
2019/07/01 Python
python实现密码强度校验
2020/03/18 Python
基于python实现地址和经纬度转换
2020/05/19 Python
keras .h5转移动端的.tflite文件实现方式
2020/05/25 Python
python 实现围棋游戏(纯tkinter gui)
2020/11/13 Python
HTML5 Canvas自定义圆角矩形与虚线示例代码
2013/08/02 HTML / CSS
Kivari官网:在线购买波西米亚服装
2018/10/29 全球购物
网络书店创业计划书
2014/02/07 职场文书
2015年学生会个人工作总结
2015/04/09 职场文书
2016年秋季趣味运动会开幕词
2016/03/04 职场文书
CSS3鼠标悬浮过渡缩放效果
2021/04/17 HTML / CSS
golang 实现Location跳转方式
2021/05/02 Golang
vue3使用vuedraggable实现拖拽功能
2022/04/06 Vue.js