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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# Interleaving two strings
# using join() + zip()
  
# initializing strings 
test_string1 = 'geeksforgeeks'
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))

chevron_right


Output :



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

 

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# Interleaving two strings
# using join() + zip() + chain.from_iterable()
from itertools import chain
  
# initializing strings 
test_string1 = 'geeksforgeeks'
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))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.