您的位置:首页 > 编程语言 > Python开发

Python - 连续替换(replace)的正則表達式(re)

2017-04-22 19:02 204 查看
字符串连续替换, 能够连续使用replace, 也能够使用正則表達式.

正則表達式, 通过字典的样式, key为待替换, value为替换成, 进行一次替换就可以.

代码

# -*- 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

"""
输出:
() and --text--
() and --text--
"""


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: