Python | Insert character after every character pair
Last Updated :
08 Sep, 2023
Sometimes, we can have a problem in which we need to insert a specific character after a pair(second) characters using Python. This kind of problem can occur while working with data, that require insertion of commas or any other special character mainly in the Machine Learning domain. Let's discuss certain ways in which this problem can be solved.
Input: GeeksforGeeks
Output: Ge, ek, sf, or, Ge, ek, s
Explanation: Here we inserted comma's after every character pair
Insert a character after every n characters in Python
Below are the methods that we will cover in this article:
Insert Character using a loop and concatenation with a separator
Define the input string test_str and then initialize an empty string res and a separator string separator. Loop through the input string concatenating every two characters with the separator then remove the trailing separator from the result string and print the original string and the result string.
Python3
# initializing string
test_str = "GeeksforGeeks"
# printing original string
print("The original string is : " + test_str)
# Using loop
# Insert character after every character pair
separator = ","
res = ""
for i in range(0, len(test_str), 2):
res += test_str[i:i + 2] + separator
# Remove the trailing separator
res = res[:-1]
# printing result
print("The string after inserting comma after every character pair : " + res)
OutputThe original string is : GeeksforGeeks
The string after inserting comma after every character pair : Ge,ek,sf,or,Ge,ek,s
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), where n is the length of the input string.
Insert Character Into String after every nth character using join() and list Comprehension
The combination of the above method can be used to perform this particular task. List comprehension along with slicing can be used to convert strings to lists and the join function can be used to rejoin them inserting required characters between them.
Python3
# initializing string
test_str = "GeeksforGeeks"
# printing original string
print("The original string is : " + test_str)
# Using join() + list comprehension
# Insert character after every character pair
res = ', '.join(test_str[i:i + 2] for i in range(0, len(test_str), 2))
# printing result
print("The string after inserting comma after every character pair : " + res)
Output:
The original string is : GeeksforGeeks
The string after inserting comma after every character pair : Ge, ek, sf, or, Ge, ek, s
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), where n is the length of the input string.
Insert characters after every Nth character using zip() and join()
The combination of the above functions can be used to perform this particular task. In this, the zip function converts the characters to iterable tuples, the split function is used to separate odd and even characters. Then list comprehension is responsible to convert the tuples to a list of strings and at last, the result is joined using the join function.
Python3
# initializing string
test_str = "GeeksforGeeks"
# printing original string
print("The original string is : " + test_str)
# Using zip() + join()
# Insert character after every character pair
res = ', '.join(a + b for a, b in zip(test_str[::2], test_str[1::2]))
# printing result
print("The string after inserting comma after every character pair : " + res)
OutputThe original string is : GeeksforGeeks
The string after inserting comma after every character pair : Ge, ek, sf, or, Ge, ek
Time complexity: O(n), where n is the length of the string test_str.
Auxiliary space: O(n), where n is the length of the res string.
Insert a character after every character pair using the Recursive method
If n is less than or equal to 2, return s otherwise, concatenate the first two characters of s with sep then recursively call insert_separator() with the remaining substring starting at index 2 after it concatenates the result of step 2 with the result of step 3 and returns the concatenated string.
Python3
def insert_separator(s, sep):
if len(s) <= 2:
return s
else:
return s[:2] + sep + insert_separator(s[2:], sep)
# Initializing the string
test_str = "GeeksforGeeks"
# Printing the original string
print("The original string is : " + test_str)
sep = ","
res = insert_separator(test_str, sep)
# Printing the result
print("The string after inserting comma after every character pair : " + res)
OutputThe original string is : GeeksforGeeks
The string after inserting comma after every character pair : Ge,ek,sf,or,Ge,ek,s
The time complexity of this function is O(n), where n is the length of the input string because it visits each character in the string exactly once.
The auxiliary space complexity of this function is O(n) because the function makes n/2 recursive calls, each of which creates a new substring of length n/2. Therefore, the maximum number of substrings that are stored in memory at any given time is n/2, and the total space required to store all substrings is O(n).
Insert character after every character pair using re
The re.sub() function takes the regular expression pattern as the first argument, the replacement string as the second argument, the two-word, and the string to search as the third argument. Here we are using regular expression (\w{2}) which will match every two-word characters and replace them with matched characters with a comma after it.
Python3
import re
# Initializing the string
test_str = "GeeksforGeeks"
# Printing the original string
print("The original string is : " + test_str)
# Using re.sub() function to insert comma after every character pair
res = re.sub(r"(\w{2})", r"\1,", test_str)
# Printing the result
print("The string after inserting comma after every character pair : " + res)
# This code is contributed by Edula Vinay Kumar Reddy
OutputThe original string is : GeeksforGeeks
The string after inserting comma after every character pair : Ge,ek,sf,or,Ge,ek,s
Time complexity: O(n)
Auxiliary Space: O(n)
Insert characters after every Nth character using the reduce() function
Initialize the string to be processed. Using the reduce() function, iterate over the string, generating pairs of characters and storing each pair in a list. Flatten the list and join the character pairs with a comma and print the final resulting string.
Python3
from functools import reduce
# Initializing the string
test_str = "GeeksforGeeks"
# Printing the original string
print("The original string is : " + test_str)
# Using reduce() function to insert comma after every character pair
res_list = reduce(
lambda x, y: x + [test_str[y:y+2]], range(0, len(test_str), 2), [])
# Flattening the list and joining the character pairs with a comma
res_str = ','.join(res_list)
# Printing the result
print("The string after inserting comma after every character pair : " + res_str)
# This code is contributed by Jyothi Pinjala.
OutputThe original string is : GeeksforGeeks
The string after inserting comma after every character pair : Ge,ek,sf,or,Ge,ek,s
Time complexity: O(n)
Space complexity: O(n)
Similar Reads
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 = 'GeeksforGeeks', K = 2, add_chr = ";" Output : [';GeeksforGeeks', 'Ge;eksforGeeks', 'Geek;sforGeeks', 'Geeksf;orGeeks', 'Geeksfor;Geeks', 'GeeksforGe;eks', 'GeeksforGeek;s'] Explanation : All combinations
3 min read
Python | Custom Consecutive Character Pairing
Sometimes, while working with Python Strings, we can have problem in which we need to perform the pairing of consecutive strings with deliminator. This can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using join() + list comprehension T
4 min read
Python - Convert list of strings and characters to list of characters
Sometimes we come forward to the problem in which we receive a list that consists of strings and characters mixed and the task we need to perform is converting that mixed list to a list consisting entirely of characters. Using itertools.chain()itertools.chain() combines multiple lists or iterables i
3 min read
Python - Insert characters at start and end of a string
In Python programming, a String is an immutable datatype. But sometimes there may come a situation where we may need to manipulate a string, say add a character to a string. Letâs start with a simple example to insert characters at the start and end of a String in Python.Pythons = "For" s2 = "Geeks"
2 min read
Python | Pair Kth character with each element
Sometimes, while working with Python, we can have a problem in which we need to perform the pairing of each character with every other in String. This can have application in many domains including web development and day-day. Lets discuss certain ways in which this task can be performed. Method #1
4 min read
Python - Extract String after Nth occurrence of K character
Given a String, extract the string after Nth occurrence of a character. Input : test_str = 'geekforgeeks', K = "e", N = 2 Output : kforgeeks Explanation : After 2nd occur. of "e" string is extracted. Input : test_str = 'geekforgeeks', K = "e", N = 4 Output : ks Explanation : After 4th occur. of "e"
7 min read
Insert after every Nth element in a list - Python
Inserting an element after every Nth item in a list is a useful way to adjust the structure of a list. For Example we have a list li=[1,2,3,4,5,6,7]Let's suppose we want to insert element 'x' after every 2 elements in the list so the list will look like li=[1,2,'x',3,4,'x',5,6,7] Iteration with inde
4 min read
Python | Replace characters after K occurrences
Sometimes, while working with Python strings, we can have a problem in which we need to perform replace of characters after certain repetitions of characters. This can have applications in many domains including day-day and competitive programming. Method #1: Using loop + string slicing This is brut
5 min read
Python program to Replace all Characters of a List Except the given character
Given a List. The task is to replace all the characters of the list with N except the given character. Input : test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'], repl_chr = '*', ret_chr = 'G' Output : ['G', '*', 'G', '*', '*', '*', '*', '*', '*'] Explanation : All characters except G replace
4 min read
Python - Remove N characters after K
Given a String, remove N characters after K character. Input : test_str = 'ge@987eksfor@123geeks is best@212 for cs', N = 3, K = '@' Output : 'geeksforgeeks is best for cs' Explanation : All 3 required occurrences removed. Input : test_str = 'geeksfor@123geeks is best for cs', N = 3, K = '@' Output
2 min read