代码之家  ›  专栏  ›  技术社区  ›  Markus

如何在Python中删除字符串中的空行?

  •  3
  • Markus  · 技术社区  · 7 年前

    我该如何扭转这种局面:

    1
    
    2
    
    3
    

    对此:

    1
    2
    3
    

    不需要将其转化为:

    123
    
    3 回复  |  直到 7 年前
        1
  •  4
  •   Lojas    7 年前
    import os
    text = os.linesep.join([s for s in text.splitlines() if s])
    
        2
  •  3
  •   Sreeram TP    7 年前

    您只需使用 replace() 喜欢 data.replace('\n\n', '\n')

    请参阅此示例以更好地理解。!!

    data = '1\n\n2\n\n3\n\n'
    print(data)
    
    data = data.replace('\n\n', '\n')
    print(data)
    

    输出

    1
    
    2
    
    3
    
    
    1
    2
    3
    
        3
  •  -1
  •   celsowm    4 年前
    text = text.replace(r"\n{2,}","\n")