在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的Twisted框架上手前所必须了解的异步编程思想
May 25 Python
Python深入06——python的内存管理详解
Dec 07 Python
详解Python pygame安装过程笔记
Jun 05 Python
python数字图像处理之高级滤波代码详解
Nov 23 Python
python中的迭代和可迭代对象代码示例
Dec 27 Python
Python操作MySQL数据库的方法
Jun 20 Python
WxPython建立批量录入框窗口
Feb 27 Python
使用Python进行体育竞技分析(预测球队成绩)
May 16 Python
python3 批量获取对应端口服务的实例
Jul 25 Python
判断Threading.start新线程是否执行完毕的实例
May 02 Python
Anaconda安装pytorch及配置PyCharm 2021环境
Jun 04 Python
Python实现文字pdf转换图片pdf效果
Apr 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
将PHP作为Shell脚本语言使用
2006/10/09 PHP
php动态生成JavaScript代码
2009/03/09 PHP
php session和cookie使用说明
2010/04/07 PHP
PHP输出Excel PHPExcel的方法
2018/07/26 PHP
PHP+fiddler抓包采集微信文章阅读数点赞数的思路详解
2019/12/20 PHP
Javascript中eval函数的使用方法与示例
2007/04/09 Javascript
js 数组克隆方法 小结
2010/03/20 Javascript
jQuery的animate函数实现图文切换动画效果
2015/05/03 Javascript
js实现div拖动动画运行轨迹效果代码分享
2015/08/27 Javascript
JS动态给对象添加事件的简单方法
2016/07/19 Javascript
jQuery基本过滤选择器用法示例
2016/09/09 Javascript
在html中引入外部js文件,并调用带参函数的方法
2016/10/31 Javascript
jquery.Jcrop结合JAVA后台实现图片裁剪上传实例
2016/11/05 Javascript
BootStrap3中模态对话框的使用
2017/01/06 Javascript
jQuery模拟下拉框选择对应菜单的内容
2017/03/07 Javascript
vue项目中使用axios上传图片等文件操作
2017/11/02 Javascript
jquery获取transform里的值实现方法
2017/12/12 jQuery
React Native之prop-types进行属性确认详解
2017/12/19 Javascript
vue项目中使用vue-i18n报错的解决方法
2019/01/13 Javascript
Node.js API详解之 assert模块用法实例分析
2020/05/26 Javascript
Python的动态重新封装的教程
2015/04/11 Python
深入理解python多进程编程
2016/06/12 Python
Python实现求两个数组交集的方法示例
2019/02/23 Python
python抓取多种类型的页面方法实例
2019/11/20 Python
美国医疗用品、医疗设备和家庭保健用品商店:Medical Supply Depot
2018/07/08 全球购物
美国在线轮胎零售商:SimpleTire
2019/04/08 全球购物
什么是Oracle的后台进程background processes?都有哪些后台进程?
2012/04/26 面试题
如何判断计算机可能已经中马
2013/03/22 面试题
人事科岗位职责范本
2014/03/02 职场文书
心理健康日活动总结
2014/05/08 职场文书
运动会铅球比赛加油稿
2014/09/26 职场文书
创业计划书之电动车企业
2019/10/11 职场文书
Python OpenCV快速入门教程
2021/04/17 Python
六种css3实现的边框过渡效果
2021/04/22 HTML / CSS
JavaScript中document.activeELement焦点元素介绍
2021/11/27 Javascript
CSS link与@import的区别和用法解析
2023/05/07 HTML / CSS