Longest consecutive substring of certain character type in python

后端 未结 2 559
旧巷少年郎
旧巷少年郎 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:16

    Regex and max with length as the key:

    In [12]: s = "43gfd54452jhg4fddsgf"
    
    In [13]: max(re.findall(r'\d+', s), key=len)  # digits
    Out[13]: '54452'
    
    In [14]: max(re.findall(r'\D+', s), key=len)  # non-digits
    Out[14]: 'fddsgf'
    

    Similarly, you can change the Regex pattern to get your desired substring type.

提交回复
热议问题