python - 用另一个替换括号中的字符
问题描述
我需要用其他东西(例如分号)替换所有出现的点,但前提是点是双亲,使用像这样的python:
输入:"Hello (This . will be replaced, this one. too)."
输出:"Hello (This ; will be replaced, this one; too)."
解决方案
假设括号是平衡的而不是嵌套的,这里有一个re.split
.
>>> import re
>>>
>>> s = 'Hello (This . will be replaced, this one. too). This ... not but this (.).'
>>> ''.join(m.replace('.', ';') if m.startswith('(') else m
...: for m in re.split('(\([^)]+\))', s))
...:
'Hello (This ; will be replaced, this one; too). This ... not but this (;).'
这里的主要技巧是\([^)]+\)
用另一对包装正则表达式,()
以便保留拆分匹配。
推荐阅读
- svg - 多个对象上的一个渐变
- vue.js - Vue Js 立即添加事件监听器触发
- sql - 使用 ts_vector 列进行文本搜索
- python - 使用 Python 在 JIRA 中使用受让人、观察者和附件创建新问题
- c# - WPF:如何为 ListView 创建自定义视图模式
- android - 如何在活动底部显示覆盖进度条
- python - 将字典项转换为 pandas 数据帧的行,其中键是元组,值是整数
- unoconv - `unoconv`没有将excel工作表的所有内容导出为pdf
- javascript - 展开所有并折叠所有可折叠手风琴物化 css
- laravel - 无法与主机 mail.veebimajutus.ee 建立 Laravel 连接 [不允许操作 #1]