![](/img/trans.png)
[英]Do not run a python script again within a specific time (e.g. 1 hour)
[英]How to remove specific characters in a string *within specific delimiters*, e.g. within parentheses
在字符串中
my_string = 'abcd (ef gh ) ij'
我只需要在括号内出现时删除空格,结果是:
my_clean_string = 'abcd (efgh) ij'
这篇文章建议如何完全通过re.sub(r'\\([^)]*\\)', '', my_string)
删除所有括号文本,但是我不知道如何指定删除只应用于空格' '
。
有没有一个regexpr(或简单的python)解决方案,而不是明确地循环每个字符?
这是一种适用于嵌套括号的通用方法:
In [27]: my_string = 'abcd ( ()e(e w )f ) gh'
In [28]: re.sub(r' \(\s+|\s+\)', lambda x: x.group().strip(), my_string)
Out[28]: 'abcd(()e(e w)f) gh'
如果你想删除即使单词之间有空格,你可以玩弄查找变通 ;-):
In [40]: my_string = 'abcd ( ()e(e w )f ) gh'
In [41]: re.sub(r'\s+(?=[^[\(]*\))|((?<=\()\s+)', '', my_string)
Out[41]: 'abcd (()e(ew)f) gh'
这将删除括号内的单词前后的空格。
import re
my_string = 'abcd ( ef dfg dfg ) gh'
print re.sub('\(\s*(.*?)\s*\)', lambda x: ''.join(x.group().split()), my_string, re.DOTALL)
输出:
abcd (efdfgdfg) gh
不使用正则表达式的解决方案,
my_string = 'abcd (ef ) gh'
str_to_replace = my_string[my_string.find('(')+1:my_string.find(')')]
out = my_string.replace(str_to_replace,str_to_replace.replace(' ',''))
结果
abcd(ef)gh
关于这篇文章 ,
re.sub("\\s+(?=[^()]*\\))", "", my_string)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.