Open In App
Related Articles

Python | Insert character after every character pair

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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)

                    

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

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

                    

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

                    

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

                    

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

                    

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)



Last Updated : 08 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads