时间:2021-07-01 10:21:17 帮助过:33人阅读
代码:
# -*- 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 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--