在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中is和id的用法
Apr 03 Python
在Python中处理字符串之isdigit()方法的使用
May 18 Python
Python实现列表转换成字典数据结构的方法
Mar 11 Python
尝试用最短的Python代码来实现服务器和代理服务器
Jun 23 Python
打包发布Python模块的方法详解
Sep 18 Python
Python 多线程实例详解
Mar 25 Python
Python简单定义与使用字典dict的方法示例
Jul 25 Python
Python网络编程基于多线程实现多用户全双工聊天功能示例
Apr 10 Python
python3.x实现base64加密和解密
Mar 28 Python
django配置app中的静态文件步骤
Mar 27 Python
Python预测2020高考分数和录取情况
Jul 08 Python
Django利用AJAX技术实现博文实时搜索
May 06 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和Mysqlweb应用开发核心技术 第1部分 Php基础-3 代码组织和重用2
2011/07/03 PHP
Thinkphp搜索时首页分页和搜索页保持条件分页的方法
2014/12/05 PHP
PHP下载远程图片的几种方法总结
2017/04/07 PHP
使用PHPExcel实现数据批量导出为excel表格的方法(必看)
2017/06/09 PHP
thinkPHP5框架路由常用知识点汇总
2019/09/15 PHP
发一个自己用JS写的实用看图工具实现代码
2008/07/26 Javascript
javascript获取元素离文档各边距离的方法
2015/02/13 Javascript
jquery对复选框(checkbox)的操作汇总
2016/01/13 Javascript
JavaScript+html5 canvas绘制缤纷多彩的三角形效果完整实例
2016/01/26 Javascript
浅谈javascript中的Function和Arguments
2016/08/30 Javascript
jQuery实现隔行变色的方法分析(对比原生JS)
2016/11/18 Javascript
浅谈js数组和splice的用法
2016/12/04 Javascript
微信小程序 textarea 详解及简单使用方法
2016/12/05 Javascript
js 去掉字符串前后空格实现代码集合
2017/03/25 Javascript
express + jwt + postMan验证实现持久化登录
2019/06/05 Javascript
Vue解析剪切板图片并实现发送功能
2020/02/04 Javascript
在Python中使用NLTK库实现对词干的提取的教程
2015/04/08 Python
python+Splinter实现12306抢票功能
2018/09/25 Python
Python3实现的简单三级菜单功能示例
2019/03/12 Python
Tensorflow模型实现预测或识别单张图片
2019/07/19 Python
python对XML文件的操作实现代码
2020/03/27 Python
python--shutil移动文件到另一个路径的操作
2020/07/13 Python
基于Canvas+Vue的弹幕组件的实现
2019/07/23 HTML / CSS
贝玲妃美国官方网站:Benefit美国
2016/08/28 全球购物
好莱坞百老汇御用王牌美妆:Koh Gen Do 江原道
2018/04/03 全球购物
GOLFINO英国官网:高尔夫服装
2020/04/11 全球购物
阿里巴巴的Oracle DBA笔试题答案-SQL tuning类
2016/04/03 面试题
食品委托检验协议书范本
2014/09/12 职场文书
优秀班集体事迹材料
2014/12/25 职场文书
客户付款通知书
2015/04/23 职场文书
开票证明
2015/06/23 职场文书
mybatis中sql语句CDATA标签的用法说明
2021/06/30 Java/Android
MySQL窗口函数的具体使用
2021/11/17 MySQL
win11无法登录onedrive错误代码0x8004def7怎么办 ?
2022/04/05 数码科技
Java完整实现记事本代码
2022/06/16 Java/Android
mysql序号rownum行号实现方式
2022/12/24 MySQL