Home > Software engineering >  counting consecutive digits in a string
counting consecutive digits in a string

Time:05-31

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

CodePudding user response:

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

CodePudding user response:

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