在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 探针的实现原理
Apr 23 Python
Python 读写文件和file对象的方法(推荐)
Sep 12 Python
python中使用%与.format格式化文本方法解析
Dec 27 Python
使用pandas对两个dataframe进行join的实例
Jun 08 Python
python_opencv用线段画封闭矩形的实例
Dec 05 Python
Numpy之random函数使用学习
Jan 29 Python
python儿童学游戏编程知识点总结
Jun 03 Python
windows中安装Python3.8.0的实现方法
Nov 19 Python
python实现飞机大战游戏(pygame版)
Oct 26 Python
Python 基于FIR实现Hilbert滤波器求信号包络详解
Feb 26 Python
python GUI库图形界面开发之PyQt5不规则窗口实现与显示GIF动画的详细方法与实例
Mar 09 Python
Python爬虫之Selenium实现窗口截图
Dec 04 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
Ajax PHP 边学边练 之三 数据库
2009/11/26 PHP
PHP日期处理函数 整型日期格式
2011/01/12 PHP
php 备份数据库代码(生成word,excel,json,xml,sql)
2013/06/23 PHP
php构造函数的继承方法
2015/02/09 PHP
PHP模拟QQ登录的方法
2015/07/29 PHP
PHP如何通过传引用的思想实现无限分类(代码简单)
2015/10/13 PHP
PHP实现限制IP访问的方法
2017/04/20 PHP
ThinkPHP 在阿里云上的nginx.config配置实例详解
2017/10/11 PHP
PHP常见数组排序方法小结
2018/08/20 PHP
jquery 常用操作方法
2010/01/28 Javascript
js中的string.format函数代码
2020/08/11 Javascript
jQuery实现动画效果的简单实例
2014/01/27 Javascript
Jquery.Form 异步提交表单的简单实例
2014/03/03 Javascript
HTML页面登录时的JS验证方法
2014/05/28 Javascript
javascript中AJAX用法实例分析
2015/01/30 Javascript
jquery实现相册一下滑动两次的方法
2015/02/09 Javascript
JavaScript实现时间倒计时跳转(推荐)
2016/06/28 Javascript
jquery实现界面无刷新加载登陆注册
2016/07/30 Javascript
Ajax与服务器(JSON)通信实例代码
2016/11/05 Javascript
Angular实现购物车计算示例代码
2017/02/21 Javascript
Node.js中的http请求客户端示例(request client)
2017/05/04 Javascript
jQuery Easyui Treegrid实现显示checkbox功能
2017/08/08 jQuery
解决webpack无法通过IP地址访问localhost的问题
2018/02/22 Javascript
Vuex 使用及简单实例(计数器)
2018/08/29 Javascript
vue 父组件中调用子组件函数的方法
2019/06/06 Javascript
跟老齐学Python之集成开发环境(IDE)
2014/09/12 Python
python中的计时器timeit的使用方法
2017/10/20 Python
django项目环境搭建及在虚拟机本地创建django项目的教程
2019/08/02 Python
django数据模型on_delete, db_constraint的使用详解
2019/12/24 Python
Python爬虫过程解析之多线程获取小米应用商店数据
2020/11/14 Python
CSS3制作日历实现代码
2012/01/21 HTML / CSS
影视制作岗位职责
2013/12/04 职场文书
公司总经理岗位职责
2014/03/15 职场文书
应届毕业生求职信
2014/05/26 职场文书
晚自修旷课检讨书怎么写
2014/11/17 职场文书
CentOS8.4安装Redis6.2.6的详细过程
2021/11/20 Redis