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
test_str = "GeeksforGeeks"
print ( "The original string is : " + test_str)
separator = ","
res = ""
for i in range ( 0 , len (test_str), 2 ):
res + = test_str[i:i + 2 ] + separator
res = res[: - 1 ]
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 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
test_str = "GeeksforGeeks"
print ( "The original string is : " + test_str)
res = ', ' .join(test_str[i:i + 2 ] for i in range ( 0 , len (test_str), 2 ))
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
test_str = "GeeksforGeeks"
print ( "The original string is : " + test_str)
res = ', ' .join(a + b for a, b in zip (test_str[:: 2 ], test_str[ 1 :: 2 ]))
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
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)
test_str = "GeeksforGeeks"
print ( "The original string is : " + test_str)
sep = ","
res = insert_separator(test_str, sep)
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
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
test_str = "GeeksforGeeks"
print ( "The original string is : " + test_str)
res = re.sub(r "(\w{2})" , r "\1," , test_str)
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)
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
test_str = "GeeksforGeeks"
print ( "The original string is : " + test_str)
res_list = reduce (
lambda x, y: x + [test_str[y:y + 2 ]], range ( 0 , len (test_str), 2 ), [])
res_str = ',' .join(res_list)
print ( "The string after inserting comma after every character pair : " + res_str)
|
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)
Space complexity: O(n)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
08 Sep, 2023
Like Article
Save Article