Find longest consecutive letter and digit substring in Python

A given string may be a mixture of digits and letters. In this article, we will find the longest consecutive substring of letters and the longest consecutive substring of digits separately using two different approaches.

Using Regular Expression Module

The regular expression module can identify all continuous substrings containing only digits or only letters. We use findall() to extract these substrings and max() with key=len to find the longest ones ?

Example

import re

def longSubstring(text):
    # Find all consecutive letter sequences
    letter = max(re.findall(r'\D+', text), key=len)
    # Find all consecutive digit sequences  
    digit = max(re.findall(r'\d+', text), key=len)
    
    return letter, digit

text = 'Hello 459 Congratulations! 234'
print(longSubstring(text))

The output of the above code is ?

(' Congratulations! ', '459')

How It Works

The pattern r'\D+' matches one or more non-digit characters (letters, spaces, punctuation), while r'\d+' matches one or more consecutive digits. The max() function uses key=len to compare sequences by their length.

Using While Loop and String Methods

This approach manually iterates through the string, building consecutive letter and digit sequences using isalpha() and isdigit() methods ?

Example

def longSubstring(s):
    max_letterSeq = ''
    max_digitSeq = ''
    i = 0
    
    while i < len(s):
        current_letterSeq = ''
        current_digitSeq = ''
        
        # Collect consecutive letters
        while i < len(s) and s[i].isalpha():
            current_letterSeq += s[i]
            i += 1
            
        # Collect consecutive digits
        while i < len(s) and s[i].isdigit():
            current_digitSeq += s[i]
            i += 1
            
        # Skip non-alphanumeric characters
        if i < len(s) and not (s[i].isdigit()) and not (s[i].isalpha()):
            i += 1
            
        # Update maximum sequences if current is longer
        if len(current_letterSeq) > len(max_letterSeq):
            max_letterSeq = current_letterSeq
            
        if len(current_digitSeq) > len(max_digitSeq):
            max_digitSeq = current_digitSeq
            
    return max_letterSeq, max_digitSeq

text = 'Hello 459 Congratulations! 234'
print(longSubstring(text))

The output of the above code is ?

('Congratulations', '459')

Comparison

Method Time Complexity Code Length Best For
Regular Expression O(n) Short Simple, readable solution
While Loop O(n) Longer Learning string traversal concepts

Conclusion

Use regular expressions for a concise solution when finding longest consecutive letter and digit substrings. The while loop approach provides better understanding of manual string processing but requires more code.

Updated on: 2026-03-15T18:27:23+05:30

467 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements