在python中使用regex删除特定字符之间的空白

2024-04-25 07:15:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用regex删除连续“?”序列中的空格和/或'!'在一根绳子里。一个例子是“那是什么?”应该改为“那是什么?”。也就是说,我想连接所有的'?'还有“!”中间没有空隙。我当前的代码运行不好:

import re
s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !"
s = re.sub("\? +\?", "??", s)
s = re.sub("\? +\!", "?!", s)
s = re.sub("\! +\!", "!!", s)
s = re.sub("\! +\?", "!?", s)

会产生“那是什么?”,其中一些空格显然没有被删除。我的代码出了什么问题,如何修改?在


Tags: 代码importrethatis序列what例子
3条回答

如果你想和@g.d.d.c说的一样,并且句型相同,那么你可以试试这个:

string_="what is that ?? ? ? ?? ??? ? ! ! ! ? !"
string_1=[]
symbols=[]
string_1.append(string_[:string_.index('?')])
symbols.append(string_[string_.index('?'):])
string_1.append("".join(symbols[0].split()))
print("".join(string_1))

输出:

^{pr2}$

我的方法是将字符串分成两部分,然后使用regex处理问题区域(删除空格),然后将这些部分重新连接起来。在

import re s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !" splitted = s.split('that ') # don't forget to add back in 'that' later splitfirst = splitted[0] s = re.sub("\s+", "", splitted[1]) finalstring = splitfirst+'that '+s print(finalstring) 输出:

╭─jc@jc15 ~/.projects/tests ╰─$ python3 string-replace-question-marks.py what is that ??????????!!!?!

你只是想压缩标点符号周围的空白,是吗?这样的怎么样:

>>> import re
>>> s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !"
>>> 
>>> re.sub('\s*([!?])\s*', r'\1', s)
'what is that??????????!!!?!'

如果您真的对为什么您的方法不起作用感兴趣,则与正则表达式如何在字符串中移动有关。当您编写re.sub("\? +\?", "??", s)并在字符串上运行它时,引擎的工作方式如下:

^{pr2}$

等等。有几种方法可以防止光标在检查匹配时前进(检查积极前瞻)。在

相关问题 更多 >