代码之家  ›  专栏  ›  技术社区  ›  Andrew Wagner

从python字符串中删除空行的快速一行程序是什么?

  •  46
  • Andrew Wagner  · 技术社区  · 16 年前

    我在python字符串中有一些包含无关空行的代码。我想删除字符串中的所有空行。做这件事最要紧的方法是什么?

    注意:我不是在寻找一个通用的代码重新格式化程序,只是一个快速的一两行程序。

    谢谢!

    9 回复  |  直到 6 年前
        1
  •  71
  •   Redwood    16 年前

    怎么样:

    text = os.linesep.join([s for s in text.splitlines() if s])
    

    哪里 text 字符串中是否包含可能的无关行?

        2
  •  14
  •   Wojciech Bederski    16 年前
    "\n".join([s for s in code.split("\n") if s])
    

    编辑2:

    text = "".join([s for s in code.splitlines(True) if s.strip("\r\n")])
    

    我想这是我的最终版本。它应该可以很好地与代码混合行结尾一起工作。我不认为带有空格的行应该被认为是空的,但是如果是空的,那么简单的s.strip()就可以了。

        3
  •  11
  •   ymv    16 年前
    filter(None, code.splitlines())
    filter(str.strip, code.splitlines())
    

    相当于

    [s for s in code.splitlines() if s]
    [s for s in code.splitlines() if s.strip()]
    

    可能对可读性有用

        4
  •  9
  •   kossboss    11 年前

    关于删除换行和带空格的空行的课程

    “T”是带有文本的变量。您将看到一个“s”变量,它是一个临时变量,只存在于主括号集的计算过程中(忘记了这些lil python的名称)。

    首先,让我们设置“t”变量,使其具有新行:

    >>> t='hi there here is\na big line\n\nof empty\nline\neven some with spaces\n       \nlike that\n\n    \nokay now what?\n'
    

    注意:还有另一种方法可以使用三引号设置变量。

    somevar="""
       asdfas
    asdf
    
      asdf
    
      asdf
    
    asdf
    """"
    

    以下是我们在没有“打印”的情况下查看时的外观:

    >>> t
    'hi there here is\na big line\n\nof empty\nline\neven some with spaces\n       \nlike that\n\n    \nokay now what?\n' 
    

    要查看实际换行,请打印它。

    >>> print t
    hi there here is
    a big line
    
    of empty
    line
    even some with spaces
    
    like that
    
    
    okay now what?
    

    命令删除所有空行(包括空格):

    所以有些新行只是新行,有些有空格,看起来像新行

    如果你想去掉所有看起来空白的行(如果它们也只有换行符或空格)

    >>> print "".join([s for s in t.strip().splitlines(True) if s.strip()])
    hi there here is
    a big line
    of empty
    line
    even some with spaces
    like that
    okay now what?
    

    或:

    >>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n").strip()])
    hi there here is
    a big line
    of empty
    line
    even some with spaces
    like that
    okay now what?
    

    注意:可以删除t.strip().splitline(true)中的strip,使其仅为t.splitlines(true),但是输出可以以额外的换行符结束(这样可以删除最后的换行符)。最后一部分s.strip(“\r\n”).strip()和s.strip()中的strip()实际上删除了换行和换行中的空格。

    命令删除所有空行(但不能删除带空格的空行):

    从技术上讲,带有空格的行不应该被认为是空的,但这一切都取决于用例以及您试图实现的目标。

    >>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n")])
    hi there here is
    a big line
    of empty
    line
    even some with spaces
    
    like that
    
    okay now what?
    

    **注意中间带**

    中间的那个条,附加在“t”变量上,只删除最后一行(正如前面的注释所述)。这是没有那条带子的样子(注意最后一行)

    使用第一个示例(删除换行符和带空格的换行符)

    >>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n").strip()])
    hi there here is
    a big line
    of empty
    line
    even some with spaces
    like that
    okay now what?
    .without strip new line here (stackoverflow cant have me format it in).
    

    第二个示例(仅删除换行符)

    >>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n")])
    hi there here is
    a big line
    of empty
    line
    even some with spaces
    
    like that
    
    okay now what?
    .without strip new line here (stackoverflow cant have me format it in).
    

    结束!

        5
  •  3
  •   sigjuice    6 年前

    通过使用 re.sub 功能

    re.sub(r'^$\n', '', s, flags=re.MULTILINE)
    
        6
  •  2
  •   peterdemin    16 年前

    这个也将删除空格行。

    re.replace(u'(?imu)^\s*\n', u'', code)

        7
  •  1
  •   jasonleonhard    8 年前

    下面是一个单行解决方案:

    print("".join([s for s in mystr.splitlines(True) if s.strip()]))
    
        8
  •  0
  •   John Machin Santi    16 年前

    现在,对于完全不同的事情:

    Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
    Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
    >>> import string, re
    >>> tidy = lambda s: string.join(filter(string.strip, re.split(r'[\r\n]+', s)), '\n')
    >>> tidy('\r\n   \n\ra\n\n   b   \r\rc\n\n')
    'a\012   b   \012c'
    

    第2集:

    这个不适用于1.5:-(

    但它不仅处理通用换行和空行,还删除尾随的空白(整理代码行时最好是imho),如果最后一个有意义的行没有终止,则执行修复作业。

    import re
    tidy = lambda c: re.sub(
        r'(^\s*[\r\n]+|^\s*\Z)|(\s*\Z|\s*[\r\n]+)',
        lambda m: '\n' if m.lastindex == 2 else '',
        c)
    
        9
  •  0
  •   Sufiyan Ghori    6 年前

    扩展YMV的答案,您可以使用 filter 具有 join 要获得所需的字符串,

    "".join(filter(str.strip, sample_string.splitlines(True)))
    
    推荐文章