您好,欢迎访问一九零五行业门户网

Python中的字符串替换操作示例

字符串的替换(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--
其它类似信息

推荐信息