Python - 连续替换(replace)的正則表達式(re)
2017-04-22 19:02
204 查看
字符串连续替换, 能够连续使用replace, 也能够使用正則表達式.
正則表達式, 通过字典的样式, key为待替换, value为替换成, 进行一次替换就可以.
代码
正則表達式, 通过字典的样式, 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-- """
相关文章推荐
- Python - 连续替换(replace)的正则表达式(re)
- Python的替换函数——strip(),replace()和re.sub()
- Python的替换函数——strip(),replace()和re.sub()
- python知识点(二):replace和re.sub运行效率比较
- Replace multiple spaces with one space in Python(替换多个空格为一个空格)
- Python常用字符串替换函数strip、replace及sub用法示例
- python使用re替换windows不支持的文件名
- python文件的replace替换
- Python中的replace()替换方法
- python 正则字符串替换 re.sub 替换输入参数字符串inStrings 所有的一个或多个空格替换为newstring
- python使用re进行字符串查找和替换
- dataframe.replace re.sub() 替换练习
- Python:re.sub()实现字符串替换
- python_基础学习_03_正则替换文本(re.sub)
- python中的replace无法替换字符串
- python正则替换操作re.sub()
- python中的re.sub replace strip
- python使用re进行字符串查找和替换
- Python学习——str.replace()方法与re.sub()方法对比
- ReplaceSaveRemoteFile 替换、保存远程图片 的代码