String substitution (interpolation), you can use string. Template, you can also use the concatenation of standard strings.
String. The template identifies the substituted character, uses the "$" symbol, or uses "${}" within the string; Use the String.substitute (dict) function when calling.
The standard string concatenation, using the "% () s" symbol, is called when the String%dict method is used.
Both can be substituted for 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 (value s) str = "' Variable:% (Var) s Escape: Percent Variable in text:% (Var) siable"
Output:
TEMPLATE: variable:foo Escape: $ Variable in text:fooiable interpolation:
Regular expression (re) for continuous substitution (replace)
strings are continuously replaced, you can use Replace in succession, or you can use regular expressions.
The regular expression, through the dictionary style, key is to be replaced, value is replaced, a replacement can be.
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--