简体   繁体   English

找不到字符串中最大长度的空格

[英]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 : 使用regex和内建的max

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

re.findall(' +', sentence) will find all the occurrences of one or more whitespaces. re.findall(' +', sentence)将查找一个或多个空格的所有出现。

map(len, ...) will transform this array into the array of the corresponding string lengths. map(len, ...)将此数组转换为相应字符串长度的数组。

max(...) will get the highest value of these string lengths. max(...)将获得这些字符串长度的最大值。

You could use a simple itertools.groupby : 您可以使用一个简单的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 ). groupby将找到连续运行的空白( is_sp == True )和连续运行的非空白( 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. 最后,剩下的唯一一件事就是选择所有长度中的最大长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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