Python - First K consecutive digits in String
Last Updated :
28 Apr, 2023
Given a String and number K, extract first K consecutive digits making number.
Input : test_str = "geeks5geeks43best", K = 2 Output : 43 Explanation : 43 is first 2 consecutive digits. Input : test_str = "geeks5gee2ks439best", K = 3 Output : 439 Explanation : 439 is first 3 consecutive digits.
Method #1 : Using loop
This is brute way in which this task can be performed. In this, we run a loop through the list and check if valid N consecutive elements are present for current digit, if yes, we return those N elements.
Python3
# Python3 code to demonstrate working of
# First K consecutive digits in String
# Using loop
# initializing string
test_str = "geeks5geeks43isbest"
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 2
# using loop to run through characters
res = ""
for idx in range(len(test_str) - K + 1):
is_num = True
# check for valid number of consecutives
for j in range(K):
is_num = is_num & test_str[idx + j].isdigit()
# extracting numbers
if is_num :
res = ""
for j in range(K):
res += test_str[idx + j]
# printing result
print("Required character digits : " + str(res))
OutputThe original string is : geeks5geeks43isbest
Required character digits : 43
Time Complexity: O(n3)
Space Complexity: O(n)
Method #2 a: Using regex()
This is yet another way in which this task can be performed. In this, we apply valid regex expression and after processing, the result is returned as occurrences, the first one is returned.
Python3
# Python3 code to demonstrate working of
# First K consecutive digits in String
# Using regex()
import re
# initializing string
test_str = "geeks5geeks43isbest"
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 2
# using regex() to solve problem
temp = re.search('\d{% s}'% K, test_str)
res = (temp.group(0) if temp else '')
# printing result
print("Required character digits : " + str(res))
OutputThe original string is : geeks5geeks43isbest
Required character digits : 43
Time Complexity: O(n)
Space Complexity: O(n)
Method 2b:Using findall() method in re module.
This is yet another way using regex in which this task can be performed. In this, we apply valid regex expression and after processing, the result is returned as occurrences, the first one is returned.
Algorithm:
- importing re module.
- Initialize the string "test_str".
- Initialize the integer "K".
- Use the "re.findall()" function to find all the occurrences of K consecutive digits in the string "test_str".
- If the resulting list from "re.findall()" is not empty, set the "res" variable to its first element.
- Print the result.
Python3
import re
# initializing string
test_str = "geeks5geeks43isbest"
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 2
# using regex.findall() to solve problem
res = re.findall('\d{% s}' % K, test_str)
if res:
res = res[0]
# printing result
print("Required character digits : " + str(res))
#this code contributed by tvsk
OutputThe original string is : geeks5geeks43isbest
Required character digits : 43
Time Complexity: O(n), where n is the length of the input string "test_str". This is because the "re.findall()" function needs to scan the entire string to find all the occurrences of the pattern.
Auxiliary Space: O(m), where m is the number of occurrences of the pattern in the input string "test_str". This is because we store the list of all the occurrences of the pattern in memory.
Method 4 : using list comprehension and string slicing
Step-by-step explanation:
The input string is initialized as test_str.
The original string is printed using print() function.
The length of the required substring is initialized as K.
List comprehension is used to generate all the possible substrings of length K in the input string. The range() function is used to iterate over all the starting positions of the substrings in the input string, and the isdigit() method is used to check if a substring consists of only digits.
The resulting list of substrings that consist of only digits is stored in the variable res.
The first matching substring is retrieved from the list res using indexing.
The resulting substring is printed using print() function.
Python3
# initializing string
test_str = "geeks5geeks43isbest"
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 2
# using list comprehension and string slicing to solve problem
res = [test_str[i:i+K] for i in range(len(test_str)-K+1) if test_str[i:i+K].isdigit()]
# getting the first match
if res:
res = res[0]
# printing result
print("Required character digits : " + str(res))
OutputThe original string is : geeks5geeks43isbest
Required character digits : 43
The time complexity of this algorithm is O(NK), where N is the length of the input string and K is the length of the required substring.
The space complexity of this algorithm is O(NK), which is the space required to store the list of all possible substrings of length K in the input string.
Similar Reads
Find Longest Consecutive Letter and Digit Substring - Python
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
4 min read
Python - Consecutive element deletion strings
Sometimes, while working with Python, we can have a problem in which we have a string and wish to extract all possible combination of words after deletion of consecutive elements one at a time. This can have application in many domains. Lets discuss certain ways in which this task can be performed.
6 min read
Python - Test if Kth character is digit in String
Given a String, check if Kth index is a digit. Input : test_str = 'geeks9geeks', K = 5 Output : True Explanation : 5th idx element is 9, a digit, hence True.Input : test_str = 'geeks9geeks', K = 4 Output : False Explanation : 4th idx element is s, not a digit, hence False. Method #1: Using in operat
5 min read
Python | Retain K consecutive elements
Sometimes while working with data, we can have a problem in which we need to select some of the elements that occur K times consecutively. This problem can occur in many domains. Let's discuss certain ways in which this problem can be solved. Method #1 : Using groupby() + list comprehension This t
8 min read
First N letters String Construction - Python
The task of constructing a string from the first N letters of a given string in Python involves extracting a specific portion of the string, starting from the beginning and including the first N characters. For example, if we have the string "GeeksForGeeks" and want to extract the first 5 characters
3 min read
Python | Consecutive element swapping in String
Sometimes, while working with strings, we can have a problem in which we may require to perform swapping of consecutive elements in string. Let's discuss certain ways in which this task can be performed. Method #1 : Using join() + zip() + generator expression The combination of above functions can b
3 min read
Python - Maximum Consecutive Substring Occurrence
Sometimes, while working with Python, we can have a problem in which we must check for substrings occurring in consecutive repetition. This can have applications in data domains. Let us discuss a way in which this task can be performed. Method #1: Using max() + re.findall() A combination of the abov
5 min read
Python - Equidistant consecutive characters Strings
Given a Strings List, extract all the strings, whose consecutive characters are at the common difference in ASCII order. Input : test_list = ["abcd", "egil", "mpsv", "abd"] Output : ['abcd', 'mpsv'] Explanation : In mpsv, consecutive characters are at distance 3. Input : test_list = ["abcd", "egil",
9 min read
Python | Split string in groups of n consecutive characters
Given a string (be it either string of numbers or characters), write a Python program to split the string by every nth character. Examples: Input : str = "Geeksforgeeks", n = 3 Output : ['Gee', 'ksf', 'org', 'eek', 's'] Input : str = "1234567891234567", n = 4 Output : [1234, 5678, 9123, 4567] Method
2 min read
Python - Consecutive K elements join in List
Sometimes, while working with Python lists, we can have a problem in which we need to join every K character into one collection. This type of application can have use cases in many domains like day-day and competitive programming. Let us discuss certain ways in which this task can be performed. Met
4 min read