简体   繁体   中英

Having trouble finding the greatest length of whitespace in string

I need to find the greatest length of white space in the string. No idea whats wrong.

def check1(x):
    cc = ()
    for i in x:
        if i != " ":
            lis.append(cc)
            cc=0
        else:
            cc +=1
            new.append(cc)
            print(cc)

I'm not sure whats wrong, its not adding to the appending list.

Use regex es and builtin max :

import re
max_len = max(map(len, re.findall(' +', sentence)))

re.findall(' +', sentence) will find all the occurrences of one or more whitespaces.

map(len, ...) will transform this array into the array of the corresponding string lengths.

max(...) will get the highest value of these string lengths.

You could use a simple itertools.groupby :

>>> from itertools import groupby
>>> s = 'foo     bar       baz          lalala'
>>> max(len(list(v)) for is_sp, v in groupby(s, str.isspace) if is_sp)
10

The groupby will find consecutive runs of whitespace ( is_sp == True ) and consecutive runs of non-whitespace ( is_sp == False ). In our case, we only care about the runs of whitespace, so we filter the non-whitespace cases away and then get the length of the consecutive runs. Finally, the only thing that is left is to pick the largest of all of lengths.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM