【问题标题】:Delete substring when it occurs once, but not when twice in a row in python当它出现一次时删除子字符串,但在python中连续两次时不删除
【发布时间】: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 都被删除了,我该如何避免呢?

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    你可以结合前瞻和后瞻断言:

    re.sub(r'\n(?!\n)(?<!\n\n)', '', test)
    

    【讨论】:

    • 谢谢。这实际上有效,而不是标记的重复
    • @Kev1n91 我也投票决定重新提出这个问题。它不是链接的副本。
    • 我喜欢这种环视顺序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 2013-12-15
    • 2012-06-05
    • 2011-11-02
    • 1970-01-01
    • 2022-07-22
    相关资源
    最近更新 更多