Find Longest Consecutive Letter and Digit Substring - Python Last Updated : 12 Feb, 2025 Summarize Comments Improve Suggest changes Share Like Article Like Report The task is to identify the longest sequence of consecutive letters or digits in a given string. A consecutive letter or digit refers to a substring where each character is adjacent to the next one in the alphabet for letters or numerically for digits. It involves identifying the longest sequence of letters and digits within a given string. For example, consider the string "3Geeksfor123geeks3". The longest consecutive letter substring would be "Geeksfor" and the longest consecutive digit substring would be "123". Using re Modulere module provides a way to extract all contiguous letter and digit sequences from the string using regular expressions. We can use re.findall() to capture sequences of letters both uppercase and lowercase and digits and max() to find the longest sequence based on length. Python import re s = '3Geeksfor123geeks3' # Extract letter and digit sequences,then find the longest a = max(re.findall(r'[a-zA-Z]+', s), key=len, default='') b = max(re.findall(r'\d+', s), key=len, default='') print(a, b) OutputGeeksfor 123 Explanation:re.findall(r'[a-zA-Z]+', s) extracts all contiguous sequences of letters both lowercase and uppercase from the string s.re.findall(r'\d+', s) extracts all contiguous sequences of digits (0-9) from the string s.max(..., key=len, default='') finds the longest sequence from each list based on the length of the sequences and if no sequences are found, it returns an empty string ('').Table of ContentUsing itertools.groupbyUsing sliding window approachUsing lamdaUsing itertools.groupbyitertools.groupby() groups consecutive characters in the string based on whether they are alphabetic or numeric. After grouping, we can iterate through the groups, updating the longest consecutive sequences for letters and digits. Python import itertools s = "Geeksfor123" a = '' # longest letter b = '' # longest digit c = '' # current letter d = '' # current digit for key, group in itertools.groupby(s, key=str.isalpha): group_str = ''.join(group) # Join the characters in the group if key: # If the group contains alphabetic characters if len(group_str) > len(c): c = group_str if len(c) > len(a): a = c else: # If the group contains digits if len(group_str) > len(d): d = group_str if len(d) > len(b): b = d print(a,b) OutputGeeksfor 123 Explanation:itertools.groupby(s, key=str.isalpha) groups consecutive alphabetic and non-alphabetic characters. ''.join(group) converts each group into a string, stored in group_str .For Letters (key = True) if the group is alphabetic, update c with the longest letter sequence. If c is longer than a, update a.For Digits (key = False) if the group is numeric, update d with the longest digit sequence. If d is longer than b, update b.Using sliding window approachSliding window technique processes the string in a single pass, maintaining variables to track the longest sequences of letters and digits. It skips over non-alphanumeric characters and updates the longest sequence dynamically. Python s = '3Geeksfor123geeks3' a = '' # longest letter b = '' # longest digit i = 0 # index pointer while i < len(s): # Track letter sequence if s[i].isalpha(): start = i # Mark the start index of the letter sequence while i < len(s) and s[i].isalpha(): # Continue while characters are alphabetic i += 1 # Update 'a' if the current letter sequence is longer a = max(a, s[start:i], key=len) # Track digit sequence elif s[i].isdigit(): start = i # Mark the start index of the digit sequence while i < len(s) and s[i].isdigit(): # Continue while characters are digits i += 1 # Update 'b' if the current digit sequence is longer b = max(b, s[start:i], key=len) # Skip non-alphanumeric characters else: i += 1 print(a, b) OutputGeeksfor 123 Explanation:First iteration first character is '3', which is not a letter or digit so i is incremented.Letter sequence next characters form the letter sequence 'Geeksfor' and a is updated to 'Geeksfor'.Digit sequence next characters form the digit sequence '123' and b is updated to '123'.Final result longest letter sequence is 'Geeksfor' and the longest digit sequence is '123'.Using lambda ExpressionsLambda functions, combined with re.findall(), allow a concise approach to extract and find the longest letter and digit sequences by comparing their lengths. This method is efficient and provides a quick solution. Python import re res = lambda s: ( max(re.findall('[a-zA-Z]+', s), key=len), # Find all letter sequences and return the longest max(re.findall('\d+', s), key=len) # Find all digit sequences and return the longest ) s = '3Geeksfor123geeks3' print(res(s)) Output('Geeksfor', '123') Explanation:re.findall(r'[a-zA-Z]+', s) extracts all letter sequences from the string s.re.findall(r'\d+', s) extracts all digit sequences from the string s.max(..., key=len, default='') finds the longest sequence by comparing lengths and returning an empty string if no sequences are found. Comment More infoAdvertise with us Next Article Find Longest Consecutive Letter and Digit Substring - Python S Smitha Dinesh Semwal Follow Improve Article Tags : Python Python Programs python-string Python string-programs Practice Tags : python Similar Reads Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo 10 min read Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth 15+ min read Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p 11 min read Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list 10 min read Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test 9 min read Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co 11 min read Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien 3 min read Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes 9 min read Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is 8 min read Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam 3 min read Like