-1

我需要从字符串中删除所有多余的空白字符,以便连续不超过 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)
4

2 回答 2

2
>>> import re
>>> s = "foo    bar  baz                        bam"
>>> len(max(re.findall(" +", s), key=len))
24
>>> re.sub(" {2,}", " ", s)
'foo bar baz bam'
于 2013-09-15T21:24:07.643 回答
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
于 2013-09-15T21:30:46.560 回答