【问题标题】:Python: Removing whitespace from multiple lines of a stringPython:从字符串的多行中删除空格
【发布时间】:2013-09-25 18:55:45
【问题描述】:

所以我需要我的程序的输出看起来像:

ababa
ab ba 
 xxxxxxxxxxxxxxxxxxx
that is it followed by a lot of spaces .
 no dot at the end
The largest run of consecutive whitespace characters was 47.

但我得到的是:

ababa

ab ba

xxxxxxxxxxxxxxxxxxx
that is it followed by a lot of spaces .
no dot at the end
The longest run of consecutive whitespace characters was 47.

当进一步查看我编写的代码时,我发现 print(c) 语句会发生这种情况:

['ababa', '', 'ab           ba ', '', '                                      xxxxxxxxxxxxxxxxxxx', 'that is it followed by a lot of spaces                         .', '                                               no dot at the end']

在某些行之间,有, '',,这可能是我的打印语句不起作用的原因。

我将如何删除它们?我尝试过使用不同的列表函数,但我不断收到语法错误。

这是我制作的代码:

  a = '''ababa

    ab           ba 

                                      xxxxxxxxxxxxxxxxxxx
that is it followed by a lot of spaces                         .
                                               no dot at the end'''


c = a.splitlines()
print(c)

#d = c.remove(" ") #this part doesnt work
#print(d)

for row in c:
    print(' '.join(row.split()))

last_char = ""
current_seq_len = 0
max_seq_len = 0

for d in a:
    if d == last_char:
        current_seq_len += 1
        if current_seq_len > max_seq_len:
            max_seq_len = current_seq_len
    else:
        current_seq_len = 1
        last_char = d
    #this part just needs to count the whitespace

print("The longest run of consecutive whitespace characters was",str(max_seq_len)+".")

【问题讨论】:

  • 什么样的逻辑从"      xxxxxxxx"创建" xxxxxxxx"??
  • 附注:remove 方法修改列表并返回None。因此,您应该执行d = c.remove(''),而只需:c.remove(''),然后c 将少一个 空字符串。要通过remove 删除所有空字符串,请执行:for _ in range(c.count('')): c.remove('')(顺便说一句:空字符串是'',即引号,没有任何空格。在您的情况下,您删除单个空格字符串:' ' quote-space-quote,你可能得到了一些 ValueErrors)

标签: python list whitespace sequence output


【解决方案1】:

正则表达式时间:

import re

print(re.sub(r"([\n ])\1*", r"\1", a))
#>>> ababa
#>>>  ab ba 
#>>>  xxxxxxxxxxxxxxxxxxx
#>>> that is it followed by a lot of spaces .
#>>>  no dot at the end

re.sub(matcher, replacement, target_string)

匹配器是r"([\n ])\1*,这意味着:

([\n ]) → match either "\n" or " " and put it in a group (#1)
\1*     → match whatever group #1 matched, 0 or more times

而替换只是

\1 → group #1

你可以得到最长的空白序列

max(len(match.group()) for match in re.finditer(r"([\n ])\1*", a))

它使用相同的匹配器,但只是获取它们的长度,然后maxs 它。

【讨论】:

    【解决方案2】:

    据我所知,您最简单的解决方案是使用list comprehension

    c= [item for item in a.splitlines() if item != '']
    

    如果您希望通过删除仅包含空格的字符串(例如' ')使其更加健壮,那么您可以按如下方式进行更改:

    c= [item for item in a.splitlines() if item.strip() != '']
    

    您也可以将其重新加入列表,如下所示:

    output = '\n'.join(c)
    

    【讨论】:

    • if item.strip() 就足够了。无需添加!= ""
    • 虽然它是真的,但为了便于阅读,我更喜欢使用显式形式。
    【解决方案3】:

    这可以通过内置的filter 函数轻松解决:

    c = filter(None, a.splitlines())
    # or, more explicit
    c = filter(lambda x: x != "", a.splitlines())
    

    第一个变体将创建一个列表,其中包含 a.splitlines() 返回的列表中不等于 False 的所有元素,例如空字符串。 第二个变体创建一个小的匿名函数(使用lambda),它检查给定元素是否为空字符串,如果是则返回False。这比第一个变体更明确。

    另一种选择是使用list comprehension 来实现相同的目的:

    c = [string for string in a.splitlines if string]
    # or, more explicit
    c = [string for string in a.splitlines if string != ""]
    

    【讨论】:

    • 这行得通。但是,如果列表中的一项是空字符串,即只是空格,例如' ',则不会被过滤掉。
    • @MichaelAquilina 如果字符串包含空格,则它不是空字符串。要检查字符串是否为空或仅包含空格,只需使用lambda x: x.strip())。不带参数的strip() 会删除字符串左右所有连续的空格,如果字符串只有空格,则会产生一个空字符串。
    • @Bakuriu 这实际上是我在回答中建议的方法。
    • 但从我从 OP 的问题中收集到的信息来看,他只处理真正的空字符串 (""),这就是为什么我没有在此处包含 strip
    猜你喜欢
    • 2015-04-21
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    相关资源
    最近更新 更多