在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 自动安装 Rising 杀毒软件
Apr 24 Python
Python实现远程调用MetaSploit的方法
Aug 22 Python
Django+Ajax+jQuery实现网页动态更新的实例
May 28 Python
浅谈Python接口对json串的处理方法
Dec 19 Python
python3 tkinter实现点击一个按钮跳出另一个窗口的方法
Jun 13 Python
python输入多行字符串的方法总结
Jul 02 Python
Django框架模型简单介绍与使用分析
Jul 18 Python
Django如何实现网站注册用户邮箱验证功能
Aug 14 Python
使用PyTorch实现MNIST手写体识别代码
Jan 18 Python
python logging.basicConfig不生效的原因及解决
Feb 20 Python
PyQt5 控件字体样式等设置的实现
May 13 Python
如何用 Python 制作一个迷宫游戏
Feb 25 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模块memcache和memcached区别分析
2011/06/14 PHP
自定义php类(查找/修改)xml文档
2013/03/26 PHP
从PHP $_SERVER相关参数判断是否支持Rewrite模块
2013/09/26 PHP
PHP常用技术文之文件操作和目录操作总结
2014/09/27 PHP
PHP实现基于回溯法求解迷宫问题的方法详解
2017/08/17 PHP
让广告代码不再影响你的网页加载速度
2006/07/07 Javascript
用客户端js实现带省略号的分页
2013/04/27 Javascript
各种页面定时跳转(倒计时跳转)代码总结
2013/10/24 Javascript
JavaScript编程的10个实用小技巧
2014/04/18 Javascript
JavaScript实现当网页加载完成后执行指定函数的方法
2015/03/21 Javascript
jQuery Ajax使用实例
2015/04/16 Javascript
高性能JavaScript循环语句和条件语句
2016/01/20 Javascript
ExtJS 4.2 Grid组件单元格合并的方法
2016/10/12 Javascript
jQuery模拟完美实现经典FLASH导航动画效果【附demo源码下载】
2016/11/09 Javascript
AngularJS中使用ngModal模态框实例
2017/05/27 Javascript
JQuery判断正整数整理小结
2017/08/21 jQuery
Webpack框架核心概念(知识点整理)
2017/12/22 Javascript
JS中数组实现代码(倒序遍历数组,数组连接字符串)
2019/12/29 Javascript
javascript递归函数定义和用法示例分析
2020/07/22 Javascript
vue-cli打包后本地运行dist文件中的index.html操作
2020/08/12 Javascript
Python 异常处理的实例详解
2017/09/11 Python
解决Python pandas df 写入excel 出现的问题
2018/07/04 Python
python实现控制台打印的方法
2019/01/12 Python
如何在Python中实现goto语句的方法
2019/05/18 Python
django中SMTP发送邮件配置详解
2019/07/19 Python
python二维键值数组生成转json的例子
2019/12/06 Python
如何基于python测量代码运行时间
2019/12/25 Python
Pytest框架之fixture的详细使用教程
2020/04/07 Python
微信html5页面调用第三方位置导航的示例
2018/03/14 HTML / CSS
GafasWorld哥伦比亚:网上购买眼镜
2017/11/28 全球购物
企业安全生产责任书范本
2014/07/28 职场文书
运动会广播稿50字-100字
2014/10/11 职场文书
批评与自我批评范文
2014/10/15 职场文书
市级三好生竞选稿
2015/11/21 职场文书
2016年优秀少先队员事迹材料
2016/02/26 职场文书
选择比努力更重要?这是长期以来对“努力”的最大误解
2019/07/12 职场文书