String Replacement Operation example in Python, python example
String replacement (interpolation). You can use string. Template or standard string concatenation.
String. Template indicates the character to be replaced. Use the "$" symbol, or use "$ {}" in the string. Use the string. substitute (dict) function for calling.
Concatenate standard strings and 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
Replace regular expression (re)
String replacement. You can use replace or regular expression consecutively.
Regular Expression. The key is to be replaced by the dictionary style, and the value is to be replaced by a regular expression.
Code
# -*- 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
Output:
() and --text--() and --text--