Python:从字符串的多行中删除空格

Python:从字符串的多行中删除空格,python,list,whitespace,sequence,output,Python,List,Whitespace,Sequence,Output,因此,我需要程序的输出如下所示: 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 spa

因此,我需要程序的输出如下所示:

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']
在一些行之间,有
,'',
,这可能是我的print语句无法工作的原因

我该如何移除它们?我尝试过使用不同的列表函数,但总是出现语法错误

这是我写的代码:

  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)+".")

这可以通过内置功能轻松解决:

c = filter(None, a.splitlines())
# or, more explicit
c = filter(lambda x: x != "", a.splitlines())
第一个变量将创建一个列表,其中包含由
a.splitlines()
返回的列表中的所有元素,这些元素的计算结果不为
False
,如空字符串。 第二个变量创建一个小型匿名函数(使用),用于检查给定元素是否为空字符串,如果是空字符串,则返回
False
。这比第一个变量更明确

另一种选择是使用实现相同功能的:

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

这可以通过内置功能轻松解决:

c = filter(None, a.splitlines())
# or, more explicit
c = filter(lambda x: x != "", a.splitlines())
第一个变量将创建一个列表,其中包含由
a.splitlines()
返回的列表中的所有元素,这些元素的计算结果不为
False
,如空字符串。 第二个变量创建一个小型匿名函数(使用),用于检查给定元素是否为空字符串,如果是空字符串,则返回
False
。这比第一个变量更明确

另一种选择是使用实现相同功能的:

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

据我所知,最简单的解决方案是:

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

c= [item for item in a.splitlines() if item.strip() != '']
output = '\n'.join(c)
然后,您还可以将其与列表重新连接在一起,如下所示:

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

据我所知,最简单的解决方案是:

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

c= [item for item in a.splitlines() if item.strip() != '']
output = '\n'.join(c)
然后,您还可以将其与列表重新连接在一起,如下所示:

c= [item for item in a.splitlines() if item.strip() != '']
output = '\n'.join(c)
正则表达式时间:

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(匹配器、替换、目标字符串)

匹配器是
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))
它使用相同的匹配器,但只获取它们的长度,然后
max
s它。

正则表达式时间:

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(匹配器、替换、目标字符串)

匹配器是
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))

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

什么样的逻辑从
“xxxxxxxx”
中创建
“xxxxxxxx”
?旁注:
remove
方法修改列表并返回
None
。因此,您不应该执行
d=c.remove(“”)
,而应该简单地执行:
c.remove(“”)
,然后
c
将少一个空字符串。要通过
remove
删除所有空字符串,请执行以下操作:
用于范围内的uuu(c.count(“”)):c.remove(“”)
(顺便说一下:空字符串是
'
,即引号,没有任何空格。在您的情况下,删除单个空格字符串时:
'
引号空格引号,您可能会遇到一些
值错误
)什么样的逻辑从
“xxxxxxxx”
中创建
“xxxxxxxx”
?旁注:
删除
方法修改列表并返回
。因此,您不应该执行
d=c.remove(“”)
,而应该简单地执行:
c.remove(“”)
,然后
c
将少一个空字符串。要通过
remove
删除所有空字符串,请执行以下操作:
用于范围内的uuu(c.count(“”)):c.remove(“”)
(顺便说一下:空字符串是
'
,即引号,没有任何空格。在您的情况下,删除单个空格字符串时:
'
引号空格引号,您可能会遇到一些
值错误
)这会奏效的。但是,如果列表中的一项是空字符串,即只有空格,如
'
,则不会将其过滤掉。@MichaelAquilina如果字符串包含空格,则它不是空字符串。要检查字符串是否为空或仅为空格,只需使用
lambda x:x.strip()
strip()
无参数删除字符串左右两侧的所有连续空格,如果字符串仅为空格,则生成空字符串。@Bakuriu这实际上是我在回答中建议的方法。但从OP的问题中可以看出,他只处理真正的空字符串(“”),这就是为什么我没有在这里包括
strip
。这会有用的。但是,如果列表中的一项是空字符串,即只有空格,如
'
,则不会将其过滤掉。@MichaelAquilina如果字符串包含空格,则它不是空字符串。要检查字符串是否为空或仅为空格,只需使用
lambda x:x.strip()
strip()
无参数删除字符串左右两侧的所有连续空格,如果字符串仅为空格,则生成空字符串。@Bakuriu这实际上是我在回答中建议的方法。但从OP的问题中可以看出,他只处理真正的空字符串(“”),这就是为什么我没有在这里包括
strip
if item.strip()
就足够了。无需添加
!=“”
。虽然这是事实,但出于可读性的考虑,我更喜欢使用显式形式。
如果item.strip()
就足够了。无需添加
!=“”
。虽然这是事实,但出于可读性考虑,我更喜欢使用显式形式。