counting consecutive digits in a string

Viewed 44

Want to perform the counting of consecutive digits in a string

for example if i have :

s = 'lucasdre246@gmail.com'
d = 'maria23antoneta2014@gmail.com' 

Expected output for string sis 3. And expected output for string d is 4 since is the max number of consecutive number of consecutive digits inside the string

2 Answers

You can use re.findall to get the consecutive numbers and get the longest group with max with len as key

s = 'lucasdre246@gmail.com'
digits = re.findall(r"\d+", s)
print(len(max(digits, key=len))) # 3

In case you can have a string with no numbers you can use the default parameter with an empty list for length 0

s = 'lucasdre@gmail.com'
digits = re.findall(r"\d+", s)
print(len(max(digits, default=[], key=len))) # 0

The following function is what you looking for:

def max_consecutive_digits(string):
    """
    Returns the maximum number of consecutive digits in a string.
    """
    max_consecutive = 0
    current_consecutive = 0
    for char in string:
        if char.isdigit():
            current_consecutive += 1
        else:
            if current_consecutive > max_consecutive:
                max_consecutive = current_consecutive
            current_consecutive = 0
    if current_consecutive > max_consecutive:
        max_consecutive = current_consecutive
    return max_consecutive
Related