Python中的字符串替换操作示例
发布时间:2020-12-16 20:34:12 所属栏目:Python 来源:网络整理
导读:字符串的替换(interpolation),可以使用string.Template,也可以使用标准字符串的拼接. string.Template标示替换的字符,使用"$"符号,或 在字符串内,使用"${}"; 调用时使用string.substitute(dict)函数. 标准字符串拼接,使用"%()s"的符号,调用时,使用string%dic
字符串的替换(interpolation),可以使用string.Template,也可以使用标准字符串的拼接. 代码: # -*- 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) 代码 # -*- coding: utf-8 -*- import re my_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-- (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |