在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之入门(二)基本数据类型
May 25 Python
TensorFlow实现Batch Normalization
Mar 08 Python
python如何通过twisted实现数据库异步插入
Mar 20 Python
详解Python基础random模块随机数的生成
Mar 23 Python
python实现BP神经网络回归预测模型
Aug 09 Python
python 叠加等边三角形的绘制的实现
Aug 14 Python
python TK库简单应用(实时显示子进程输出)
Oct 29 Python
基于python求两个列表的并集.交集.差集
Feb 10 Python
python自定义函数def的应用详解
Jun 03 Python
python使用多线程查询数据库的实现示例
Aug 17 Python
PyChon中关于Jekins的详细安装(推荐)
Dec 28 Python
python 算法题——快乐数的多种解法
May 27 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适配器模式(Adapter)
2014/11/25 PHP
PHP使用NuSOAP调用Web服务的方法
2015/07/18 PHP
PHP严重致命错误处理:php Fatal error: Cannot redeclare class or function
2017/02/05 PHP
php插入mysql数据返回id的方法
2018/05/31 PHP
Dom与浏览器兼容性说明
2010/10/25 Javascript
输入密码检测大写是否锁定js实现代码
2012/12/03 Javascript
dwz 如何去掉ajaxloading具体代码
2013/05/22 Javascript
jQuery大于号(&gt;)选择器的作用解释
2015/01/13 Javascript
JavaScript中常见的字符串操作函数及用法汇总
2015/05/04 Javascript
jquery实现TAB选项卡鼠标经过带延迟效果的方法
2015/07/27 Javascript
三分钟带你玩转jQuery.noConflict()
2016/02/15 Javascript
jquery中用jsonp实现搜索框功能
2016/10/18 Javascript
Bootstrap源码解读模态弹出框(11)
2016/12/28 Javascript
Bootstrap模态框案例解析
2017/03/05 Javascript
深入理解Vue生命周期、手动挂载及挂载子组件
2017/09/27 Javascript
微信小程序实现的涂鸦功能示例【附源码下载】
2018/01/12 Javascript
基于Bootstrap下拉框插件bootstrap-select使用方法详解
2018/08/07 Javascript
小程序实现五星点评效果
2018/11/03 Javascript
JavaScript 作用域实例分析
2019/10/02 Javascript
Python首次安装后运行报错(0xc000007b)的解决方法
2016/10/18 Python
Python基于回溯法子集树模板解决全排列问题示例
2017/09/07 Python
基于python socketserver框架全面解析
2017/09/21 Python
Python编程给numpy矩阵添加一列方法示例
2017/12/04 Python
python连接mongodb密码认证实例
2018/10/16 Python
python 将大文件切分为多个小文件的实例
2019/01/14 Python
基于Python的微信机器人开发 微信登录和获取好友列表实现解析
2019/08/21 Python
python写入数据到csv或xlsx文件的3种方法
2019/08/23 Python
pandas DataFrame运算的实现
2020/06/14 Python
HTML最新标准HTML5总结(必看)
2016/06/13 HTML / CSS
深入浅析HTML5中的article和section的区别
2018/05/15 HTML / CSS
2019年.net常见面试问题
2012/02/12 面试题
九一八事变纪念日演讲稿
2014/09/14 职场文书
详解MySQL集群搭建
2021/05/26 MySQL
Python机器学习之基于Pytorch实现猫狗分类
2021/06/08 Python
详解overflow:hidden的作用(溢出隐藏、清除浮动、解决外边距塌陷)
2021/07/01 HTML / CSS
Python中的变量与常量
2021/11/11 Python