
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Longest Consecutive Letter and Digit Substring in Python
A given string may be a mixture of digits and letters. In this article we are required to find the biggest substring that has letters and digits together.
with re module
The regular expression module can be used to find all the continuous substring having digits or letters. Then we apply the max function to pick only those continuous substrings of letters and digits which have maximum length among all the substrings found. The findall function is also use to identify and get the required substrings.
Example
import re def longSubstring(str): letter = max(re.findall(r'\D+', str), key=len) digit = max(re.findall(r'\d+', str), key=len) return letter, digit str = 'Hello 459 Congratulations! 234' print(longSubstring(str))
Output
Running the above code gives us the following result −
(' Congratulations! ', '459')
With len() and While Loop
This is a straight but slow approach in which we design while loops to check the length of digits and letters present as substring in the given string. Then we compare their lengths and choose only the substrings with maximum length.
Example
def longSubstring(s): max_letterSeq = '' max_digitSeq = '' i = 0 while (i < len(s)): current_letterSeq = '' current_digitSeq = '' # Letters while (i < len(s) and s[i].isalpha()): current_letterSeq += s[i] i += 1 # Digits while (i < len(s) and s[i].isdigit()): current_digitSeq += s[i] i += 1 # Check if not digit or alphabet if (i < len(s) and not (s[i].isdigit()) and not (s[i].isalpha())): i += 1 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 str = 'Hello 459 Congratulations! 234' print(longSubstring(str))
Output
Running the above code gives us the following result −
('Congratulations', '459')