Python Program to split string into k sized overlapping strings
Last Updated :
22 Apr, 2023
Given a string, the task is to write a Python program to extract overlapping consecutive string slices from the original string according to size K.Â
Example:
Input : test_str = 'Geeksforgeeks', K = 4
Output : ['Geek', 'eeks', 'eksf', 'ksfo', 'sfor', 'forg', 'orge', 'rgee', 'geek', 'eeks']
Explanation : Consecutive overlapping 4 sized strings are output.
Input : test_str = 'Geeksforgeeks', K = 6
Output : ['Geeksf', 'eeksfo', 'eksfor', 'ksforg', 'sforge', 'forgee', 'orgeek', 'rgeeks']
Explanation : Consecutive overlapping 6 sized strings are output.
Method 1: Using islice() + generator function + join()Â
In this, windows of size K are extracted using the islice(), and results are yielded in an intermediate way using yield. The final results are joined using join().Â
Python3
# Python3 code to demonstrate working of
# Overlapping consecutive K splits
# Using islice() + generator function + join()
from itertools import islice
# generator function
def over_slice(test_str, K):
itr = iter(test_str)
res = tuple(islice(itr, K))
if len(res) == K:
yield res
for ele in itr:
res = res[1:] + (ele,)
yield res
# initializing string
test_str = 'Geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# calling generator function
res = ["".join(ele) for ele in over_slice(test_str, K)]
# printing result
print("Overlapping windows : " + str(res))
Output:
The original string is : Geeksforgeeks
Overlapping windows : ['Geek', 'eeks', 'eksf', 'ksfo', 'sfor', 'forg', 'orge', 'rgee', 'geek', 'eeks']
Method 2: Using list comprehension + slicing
In this example, intermediate slices are performed using a slicing operation in a more pythonic way. Each window is extracted using slice notation.
Python3
# Python3 code to demonstrate working of
# Overlapping consecutive K splits
# Using list comprehension + slicing
# initializing string
test_str = 'Geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# extracting window using slicing
res = [test_str[idx:idx + K] for idx in range(len(test_str) - K + 1)]
# printing result
print("Overlapping windows : " + str(res))
Output:
The original string is : Geeksforgeeks
Overlapping windows : ['Geek', 'eeks', 'eksf', 'ksfo', 'sfor', 'forg', 'orge', 'rgee', 'geek', 'eeks']Â
The Time and Space Complexity of all the methods is :
Time Complexity: O(n)
Space Complexity: O(n)
Method 3: Â Using recursion :
Â
Python3
# Python3 code to demonstrate working of
# Overlapping consecutive K splits
# Using recursion
# initializing string
test_str = 'Geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# recursive function
def over_slice(test_str, K, res = []):
# if length of string is less
if (len(test_str) < K):
return
# append the string
res.append(test_str[:K])
# call recursively
over_slice(test_str[1:], K, res)
# return result
return res
# calling recursive function
res = over_slice(test_str, K)
# printing result
print("Overlapping windows : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original string is : Geeksforgeeks
Overlapping windows : ['Geek', 'eeks', 'eksf', 'ksfo', 'sfor', 'forg', 'orge', 'rgee', 'geek', 'eeks']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 4 : using the windowed() function from the more_itertools module.Â
This function takes an iterable and a window size, and returns an iterator over overlapping windows of the specified size.Â
The steps for this approach are:
Import the windowed() function from the more_itertools module.
Initialize a list containing the string to be split.
Use the windowed() function to get an iterator over overlapping windows of size K.
Use a list comprehension to join each window of characters into a string.
Return the list of overlapping windows.
Python3
# Python3 code to demonstrate working of
# Overlapping consecutive K splits
# Using windowed() function from more_itertools module
from more_itertools import windowed
# initializing string
test_str = 'Geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 4
# converting string to list of characters
str_list = list(test_str)
# using windowed() function to get overlapping windows
windows = windowed(str_list, K, step=1)
# using list comprehension to join windows into strings
res = ["".join(w) for w in windows]
# printing result
print("Overlapping windows : " + str(res))
OUTPUT :
The original string is : Geeksforgeeks
Overlapping windows : ['Geek', 'eeks', 'eksf', 'ksfo', 'sfor', 'forg', 'orge', 'rgee', 'geek', 'eeks']
The time complexity of this approach is O(N), since the windowed() function is a generator and only generates the windows as they are needed, without precomputing them all at once.Â
The auxiliary space complexity is O(NK), since we need to store all the overlapping windows in a list.
Similar Reads
Python program to split a string by the given list of strings
Given a list of strings. The task is to split the string by the given list of strings. Input : test_str = 'geekforgeeksbestforgeeks', sub_list = ["best"] Output : ['geekforgeeks', 'best', 'forgeeks'] Explanation : "best" is extracted as different list element. Input : test_str = 'geekforgeeksbestfor
4 min read
Python program to find Indices of Overlapping Substrings
To count the number of overlapping sub-strings in Python we can use the Re module. To get the indices we will use the re.finditer() method. But it returns the count of non-overlapping indices only. Examples: Input: String: "geeksforgeeksforgeeks" ; Pattern: "geeksforgeeks" Output: [0, 8] Explanation
4 min read
Python program to convert String to K sized Numerical Rows
Given a string of alphabets, convert it to K sized numerical rows, which contain the number being the positional value of characters. Input : test_str = 'geeksforgeek', K = 4 Output : [[6, 4, 4, 10], [18, 5, 14, 17], [6, 4, 4, 10]] Explanation : g is at 6th position in alphabet hence gâ 6 and the st
5 min read
Python | Split CamelCase string to individual strings
Given a string in a camel-case, write a Python program to split each word in the camel case string into individual strings. Examples: Input : "GeeksForGeeks" Output : ['Geeks', 'For', 'Geeks'] Input : "ThisIsInCamelCase" Output : ['This', 'Is', 'In', 'Camel', 'Case'] Method #1: Naive Approach A naiv
4 min read
Python program to remove K length words in String
Given a String, write a Python program to remove all the words with K length. Examples: Input : test_str = 'Gfg is best for all geeks', K = 3 Output : is best geeks Explanation : Gfg, for and all are of length 3, hence removed. Input : test_str = 'Gfg is best for all geeks', K = 2 Output : Gfg best
5 min read
Python | Count overlapping substring in a given string
Given a string and a sub-string, the task is to get the count of overlapping substring from the given string. Note that in Python, the count() function returns the number of substrings in a given string, but it does not give correct results when two occurrences of the substring overlap. Consider thi
2 min read
Splitting String to List of Characters - Python
The task of splitting a string into a list of characters in Python involves breaking down a string into its individual components, where each character becomes an element in a list. For example, given the string s = "GeeksforGeeks", the task is to split the string, resulting in a list like this: ['G
3 min read
Splitting String to List of Characters - Python
We are given a string, and our task is to split it into a list where each element is an individual character. For example, if the input string is "hello", the output should be ['h', 'e', 'l', 'l', 'o']. Let's discuss various ways to do this in Python.Using list()The simplest way to split a string in
2 min read
Python program to repeat M characters of a string N times
In this article, the task is to write a Python program to repeat M characters of string N times. Method 1: Define a function that will take a word, m, and n values as arguments.If M is greater than the length of the word. Set m value equal to the length of the wordNow store the characters needed to
3 min read
Python | Splitting string list by strings
Sometimes, while working with Python strings, we might have a problem in which we need to perform a split on a string. But we can have a more complex problem of having a front and rear string and need to perform a split on them. This can be multiple pairs for split. Let's discuss certain way to solv
3 min read