从字符串中删除多余的空格(并计算它们)

时间:2013-09-15 21:20:36

标签: python python-3.x

我需要从字符串中删除所有多余的空白字符,以便连续不超过1个。我还需要打印一行,其中包含删除的最大连续数量的空格字符。

这是我到目前为止所做的,但它现在所做的就是将字符串返回给我。

def spaceremover(text):
    for i in range(1,len(text)):
        if i==' ':
            if text[i-1]==' ':
                del i


def spacecounter(text):
    count=0
    maxcount=0
    for i in range(1,len(text)):
        if i==' ':
            if text[i-1]==' ':
                count=count+1
        elif count>maxcount:
           maxcount=count
            count=0
        else: 
            count=0
    return maxcount


def main(text):
    spacecounter(text)
    spaceremover(text)
    text=''.join(text)
    print (text)

text=list(input())
main(text)

2 个答案:

答案 0 :(得分:2)

>>> import re
>>> s = "foo    bar  baz                        bam"
>>> len(max(re.findall(" +", s), key=len))
24
>>> re.sub(" {2,}", " ", s)
'foo bar baz bam'

答案 1 :(得分:1)

通常情况下,我会使用正则表达式,但由于已经提出过,这里有一个更简单的DIY方法(仅仅是为了完整性):

def countSpaces(s):
    answer = []
    start = None
    maxCount = 0
    for i,char in enumerate(s):
        if char == ' ':
            if start is None:
                start = i
                answer.append(char)
        else:
            if start is not None:
                maxCount = max(i-start-1, maxCount)
                start = None
            answer.append(char)
    print("The whitespace normalized string is", ''.join(answer))
    print("The maximum length of consecutive whitespace is", maxCount)

输出:

>>> s = "foo    bar  baz                        bam"
>>> countSpaces(s)
The whitespace normalized string is foo bar baz bam
The maximum length of consecutive whitespace is 23