Python – Insert character in each duplicate string after every K elements

Given a string and a character, insert a character after every K occurrence.
Input : test_str = ‘zambiatek’, K = 2, add_chr = “;”
Output : [‘;zambiatek’, ‘Ge;eksforGeeks’, ‘Geek;sforGeeks’, ‘Geeksf;orGeeks’, ‘Geeksfor;Geeks’, ‘GeeksforGe;eks’, ‘GeeksforGeek;s’]
Explanation : All combinations after adding ; after every K elements.Input : test_str = ‘zambiatek’, K = 2, add_chr = “*”
Output : [‘*zambiatek’, ‘Ge*eksforGeeks’, ‘Geek*sforGeeks’, ‘Geeksf*orGeeks’, ‘Geeksfor*Geeks’, ‘GeeksforGe*eks’, ‘GeeksforGeek*s’]
Explanation : All combinations after adding * after every K elements.
Method 1: Using loop + slicing
This is one of the ways in which this task can be performed. In this, we slice string on every Kth occurrence using string slicing and append characters between them.
Python3
# Python3 code to demonstrate working of# Insert character after every K elements# Using loop + string slicing# Function to Insert character# in each duplicate string# after every K elementsdef insertCharacterAfterKelements(test_str, K, char): res = [] # using loop to iterate for idx in range(0, len(test_str), K): # appending all the results res.append(test_str[:idx] + char + test_str[idx:]) return str(res)# Driver Code# initializing stringinput_str = 'zambiatek'# printing original stringprint("The original string is : " + str(input_str))# initializing KK = 2# initializing add charadd_chr = ";"# printing resultprint("The extracted strings : " + insertCharacterAfterKelements(input_str, K, add_chr)) |
The original string is :zambiatek The extracted strings : [';zambiatek', 'Ge;eksforGeeks', 'Geek;sforGeeks', 'Geeksf;orGeeks', 'Geeksfor;Geeks', 'GeeksforGe;eks', 'GeeksforGeek;s']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2: Using (list comprehension + slicing)
This is yet another way in which this task can be performed. In this, we perform a similar task as loop difference being that list comprehension is employed as shorthand to solve this question.
Python3
# Python3 code to demonstrate working of# Insert character after every K elements# Using list comprehension + string slicing# Function to Insert character# in each duplicate string# after every K elementsdef insertCharacterAfterKelements(test_str, K, char): # list comprehension to bind logic in one. res = [test_str[:idx] + char + test_str[idx:] for idx in range(0, len(test_str), K)] return str(res)# Driver Code# initializing stringinput_str = 'zambiatek'# printing original stringprint("The original string is : " + str(input_str))# initializing KK = 2# initializing add charadd_chr = ";"# printing resultprint("The extracted strings : " + insertCharacterAfterKelements(input_str, K, add_chr)) |
The original string is :zambiatek The extracted strings : [';zambiatek', 'Ge;eksforGeeks', 'Geek;sforGeeks', 'Geeksf;orGeeks', 'Geeksfor;Geeks', 'GeeksforGe;eks', 'GeeksforGeek;s']
Time Complexity: O(n)
Auxiliary Space: O(n)



