For string replacement (interpolation), you can use string.Template, or you can use standard string concatenation.
string.Template indicates the replaced characters, using the "$" symbol, or within the string, using "${}"; use the string.substitute(dict) function when calling.
For standard string concatenation, use the "%()s" symbol. When calling, use the string%dict method.
Both can replace characters.
Code:
# -*- 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
Output:
TEMPLATE: Variable : foo Escape : $ Variable in text : fooiable INTERPOLATION: Variable : foo Escape : % Variable in text : fooiable
Regular expression (re) for continuous replacement (replace)
Continuous string replacement, you can use replace continuously, or you can use regular expressions.
Regular expression, through the dictionary style, the key is to be replaced, the value is to be replaced, and it can be replaced once.
Code
# -*- 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
Output:
() and --text-- () and --text--