Longest consecutive substring of certain character type in python

后端 未结 2 525
旧巷少年郎
旧巷少年郎 2021-01-26 19:37

Is there a pythonic way to find the length of the longest consecutive substring of a certain character type, for instance the length of the longest consecutive substrings of dig

2条回答
  •  星月不相逢
    2021-01-26 20:08

    If there are always "**" between each substring. All you have to do is iterate over the different elements, keeping in a variable the longest substring you have found so far.

    longest_letter = 0
    longest_digit = 0
    for el in s.split("**"):
        if(el.isalpha()):
            len_letter = len(el)
            if(len_letter > longest_letter):
                longest_letter = len_letter
        if(el.isdigit()):
            len_digit = len(el)
            if(len_digit > longest_digit):
                longest_digit = len_digit
    print (longest_letter)
    print (longest_digit)
    

提交回复
热议问题