Open In App

Python – First K consecutive digits in String

Last Updated : 28 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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))


Output

The 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))


Output

The 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:

  1. importing re module.
  2. Initialize the string “test_str”.
  3. Initialize the integer “K”.
  4. Use the “re.findall()” function to find all the occurrences of K consecutive digits in the string “test_str”.
  5. If the resulting list from “re.findall()” is not empty, set the “res” variable to its first element.
  6. 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


Output

The 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))


Output

The 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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads