Python中的字符串替换操作示例

字符串的替换(interpolation), 可以使用string.Template, 也可以使用标准字符串的拼接.
string.Template标示替换的字符, 使用”$”符号, 或 在字符串内, 使用”${}”; 调用时使用string.substitute(dict)函数.
标准字符串拼接, 使用”%()s”的符号, 调用时, 使用string%dict方法.
两者都可以进行字符的替换.

代码:

# -*- coding: utf-8 -*-  import string  values = {'var' : 'foo'}  tem = string.Template(''''' Variable : $var Escape : $$ Variable in text : ${var}iable ''')  print 'TEMPLATE:', tem.substitute(values)  str = ''''' Variable : %(var)s Escape : %% Variable in text : %(var)siable '''  print 'INTERPOLATION:', str%values 

登录后复制

输出:

TEMPLATE:  Variable : foo Escape : $ Variable in text : fooiable  INTERPOLATION:  Variable : foo Escape : % Variable in text : fooiable 

登录后复制

连续替换(replace)的正则表达式(re)
字符串连续替换, 可以连续使用replace, 也可以使用正则表达式.
正则表达式, 通过字典的样式, key为待替换, value为替换成, 进行一次替换即可.

代码

# -*- coding: utf-8 -*-import remy_str = "(condition1) and --condition2--"print my_str.replace("condition1", "").replace("condition2", "text")rep = {"condition1": "", "condition2": "text"}rep = dict((re.escape(k), v) for k, v in rep.iteritems())pattern = re.compile("|".join(rep.keys()))my_str = pattern.sub(lambda m: rep[re.escape(m.group(0))], my_str)print my_str

登录后复制

输出:

() and --text--() and --text--

登录后复制

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2286241.html

(0)
上一篇 2025年2月27日 21:56:44
下一篇 2025年2月19日 10:53:24

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论