【发布时间】:2018-03-02 21:03:07
【问题描述】:
我知道如何删除或替换子字符串。但我只在子字符串不重复出现的情况下才想要它。我做了一个看起来很丑陋的解决方法,我想知道是否有更好的解决方案。
假设以下字符串:
test = "Hello\n,I am here now.\n\nSo what's the problem?"
第一个"\n" 应该被删除,但第二个"\n\n" 不应该。
为此,我将"\n\n" 替换为不会出现在正常会话字符串中的内容,例如:
x = test.replace('\n\n','42#*#')
x = x.replace('\n','')
x = x.replace('42#*#','\n\n')
哪个可行,但我想知道是否有更好的解决方案来解决这个问题?
编辑:我尝试了Split a string on a certain character only if it doesn't follow directly after another particular character的解决方案
但是,当使用以下正则表达式时:
re.split('(?<!,)\n', test)
我会得到以下结果:
['Hello', ',I am here now.', '', "So what's the problem?"]
所以\n 和\n\n 都被删除了,我该如何避免呢?
【问题讨论】: