在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 相关文章推荐
Ubuntu 16.04 LTS中源码安装Python 3.6.0的方法教程
Dec 27 Python
深入理解Python对Json的解析
Feb 14 Python
Python 调用Java实例详解
Jun 02 Python
python使用pyqt写带界面工具的示例代码
Oct 23 Python
用Python进行简单图像识别(验证码)
Jan 19 Python
详解Django解决ajax跨域访问问题
Aug 24 Python
Pycharm 实现下一个文件引用另外一个文件的方法
Jan 17 Python
利用Python库Scapy解析pcap文件的方法
Jul 23 Python
对Pytorch神经网络初始化kaiming分布详解
Aug 18 Python
Python代码块及缓存机制原理详解
Dec 13 Python
Python3将ipa包中的文件按大小排序
Apr 17 Python
Python import模块的缓存问题解决方案
Jun 02 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
Cannot modify header information错误解决方法
2008/10/08 PHP
php 什么是PEAR?
2009/03/19 PHP
PHP 读取大文件并显示的简单实例(推荐)
2016/08/12 PHP
php实现连接access数据库并转txt写入的方法
2017/02/08 PHP
PHP封装的简单连接MongoDB类示例
2019/02/13 PHP
PHP实现对数字分隔加千分号的方法
2019/03/18 PHP
指定js可访问其它域名的cookie的方法
2007/09/18 Javascript
javascript XMLHttpRequest对象全面剖析
2010/04/24 Javascript
javascript 触发HTML元素绑定的函数
2010/09/11 Javascript
Javascript类定义语法,私有成员、受保护成员、静态成员等介绍
2011/12/08 Javascript
自己写的兼容ie和ff的在线文本编辑器类似ewebeditor
2012/12/12 Javascript
javascript确认框的三种使用方法
2013/12/17 Javascript
javascript计算星座属相(十二生肖属相)示例代码
2014/01/09 Javascript
使用jQuery异步加载 JavaScript脚本解决方案
2014/04/20 Javascript
JavaScript实现的一个计算数字步数的算法分享
2014/12/06 Javascript
JS输入用户名自动显示邮箱后缀列表的方法
2015/01/27 Javascript
利用ES6语法重构React组件详解
2017/03/02 Javascript
Vuejs入门教程之Vue生命周期,数据,手动挂载,指令,过滤器
2017/04/19 Javascript
Easyui ueditor 整合解决不能编辑的问题(推荐)
2017/06/25 Javascript
Vue实战之vue登录验证的实现代码
2017/10/31 Javascript
详解微信小程序文件下载--视频和图片
2019/04/24 Javascript
vue实现商城秒杀倒计时功能
2019/12/12 Javascript
python版DDOS攻击脚本
2019/06/12 Python
Python Subprocess模块原理及实例
2019/08/26 Python
Python使用pdb调试代码的技巧
2020/05/03 Python
Keras 切换后端方式(Theano和TensorFlow)
2020/06/19 Python
Django利用elasticsearch(搜索引擎)实现搜索功能
2020/11/26 Python
泰国网上购物:Shopee泰国
2018/09/14 全球购物
捷克街头、运动和滑板一站式商店:BoardStar.cz
2019/10/06 全球购物
学院书画协会部门岗位职责
2013/12/01 职场文书
幼儿园秋季开学寄语
2014/08/02 职场文书
简单的辞职信范文(2016最新版)
2015/05/12 职场文书
钱学森观后感
2015/06/04 职场文书
实习单位鉴定意见
2015/06/04 职场文书
使用Djongo模块在Django中使用MongoDB数据库
2021/06/20 Python
5个实用的JavaScript新特性
2022/06/16 Javascript