Saturday, November 16, 2024
Google search engine
HomeLanguagesPython | Interleaving two strings

Python | Interleaving two strings

Sometimes, while working with strings, we have the task of combining two strings, i.e interleaving them according to utility. This type of utility is mostly useful while writing codes for games. Let’s discuss certain ways in which this can be performed. 

Method #1 : Using join() + zip() This task can be performed using the above functions. In this join function performs the task of joining of each element pair two strings at an index and zip performs the task of interleaving character at each string. 

Python3




# Python3 code to demonstrate
# Interleaving two strings
# using join() + zip()
 
# initializing strings
test_string1 = 'neveropen'
test_string2 = 'computerfreak'
 
# printing original strings
print("The original string 1 : " + test_string1)
print("The original string 2 : " + test_string2)
 
# using join() + zip()
# Interleaving two strings
res = "".join(i + j for i, j in zip(test_string1, test_string2))
     
# print result
print("The Interleaved string : " + str(res))


Output : 

 
The original string 1 : neveropen
The original string 2 : computerfreak
The Interleaved string : gceoemkpsuftoerrgfereekask

Time Complexity: O(n), where n is the length of the shorter input string.

Space Complexity: O(n)

Method #2 : Using zip() + join() + chain.from_iterable() This task can also be performed using the chain.from_iterable function. The major advantage to use this particular function is that it offers more speed than the above method, about 3 times faster than above method as it converts the string to iterable. 

Python3




# Python3 code to demonstrate
# Interleaving two strings
# using join() + zip() + chain.from_iterable()
from itertools import chain
 
# initializing strings
test_string1 = 'neveropen'
test_string2 = 'computerfreak'
 
# printing original strings
print("The original string 1 : " + test_string1)
print("The original string 2 : " + test_string2)
 
# using join() + zip() + chain.from_iterable()
# Interleaving two strings
res = "".join(list(chain.from_iterable(zip(test_string1, test_string2))))
     
# print result
print("The Interleaved string : " + str(res))


Output : 

 
The original string 1 : neveropen
The original string 2 : computerfreak
The Interleaved string : gceoemkpsuftoerrgfereekask

Method #3 : Using the map() and lambda function:

We use the built-in map() function to apply a lambda function to each pair of characters from the two strings. The zip() function is used to combine the characters from the two strings into pairs. The lambda function takes a pair of characters, x, and returns a string consisting of the two characters concatenated together. The map() function returns an iterator that applies the lambda function to each pair of characters, returning a list of the results.

Python3




def interleave_strings(string1, string2):
    # use map() to apply a lambda function to each pair of characters
    # from the two strings, returning a list of the results
    res = list(map(lambda x: x[0] + x[1], zip(string1, string2)))
     
    # join the list of characters into a single string and return it
    return "".join(res)
 
# test the function
test_string1 = 'neveropen'
test_string2 = 'computerfreak'
 
# printing original strings 
print("The original string 1 : " + test_string1)
print("The original string 2 : " + test_string2)
 
print("The Interleaved string : " + interleave_strings(test_string1, test_string2))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original string 1 : neveropen
The original string 2 : computerfreak
The Interleaved string : gceoemkpsuftoerrgfereekask

Time Complexity: O(N)
Auxiliary Space: O(N)

Method 4 : Use a loop to iterate over the characters of the strings and concatenate them one by one.

Step by step approach:

  • Initialize an empty string as the result.
  • Determine the length of the shorter string using the min() function.
  • Loop from 0 to the length of the shorter string.
  • In each iteration, concatenate the i-th character of both strings to the result string.
  • After the loop, add the remaining characters of the longer string to the result string.
  • Return the result string.

Python3




def interleave_strings(string1, string2):
    result = ""
    min_len = min(len(string1), len(string2))
    for i in range(min_len):
        result += string1[i] + string2[i]
    result += string1[min_len:] + string2[min_len:]
    return result
 
# test the function
test_string1 = 'neveropen'
test_string2 = 'computerfreak'
 
# printing original strings 
print("The original string 1 : " + test_string1)
print("The original string 2 : " + test_string2)
 
print("The Interleaved string : " + interleave_strings(test_string1, test_string2))


Output

The original string 1 : neveropen
The original string 2 : computerfreak
The Interleaved string : gceoemkpsuftoerrgfereekask

Time complexity: O(min(len(string1), len(string2))), because the function iterates over the characters of the shorter string, which has a maximum length of min(len(string1), len(string2)).
Auxiliary space: O(max(len(string1), len(string2))), because the function creates a result string with a length equal to the sum of the lengths of string1 and string2.

RELATED ARTICLES

Most Popular

Recent Comments