字符串的替換(interpolation), 可以使用string.Template, 也可以使用標準字符串的拼接.
string.Template標示替換的字符, 使用"$"符號, 或 在字符串內, 使用"${}"; 調用時使用string.substitute(dict)函數.
標準字符串拼接, 使用"%()s"的符號, 調用時, 使用string%dict方法.
兩者都可以進行字符的替換.
代碼:
# -*- 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 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輸出:
() and --text--() and --text--
新聞熱點
疑難解答
圖片精選