Lucas Dresl
Lucas Dresl

Reputation: 1170

counting consecutive digits in a string

Want to perform the counting of consecutive digits in a string

for example if i have :

s = '[email protected]'
d = '[email protected]' 

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

Upvotes: 2

Views: 169

Answers (2)

Guy
Guy

Reputation: 50809

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

s = '[email protected]'
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 = '[email protected]'
digits = re.findall(r"\d+", s)
print(len(max(digits, default=[], key=len))) # 0

Upvotes: 2

Burak Özalp
Burak Özalp

Reputation: 51

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

Upvotes: 0

Related Questions