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 : Using loop
This task can be performed using loop. This a brute force manner in which this task can be performed. In this, we iterate each character and append the Kth letter to each and construct a list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Pair Kth character with each element
# Using loop
  
# initializing string
test_str = "geeksforgeeks"
  
# printing original string
print("The original string is : " + test_str)
  
# initializing K 
K = 4
  
# Pair Kth character with each element
# Using loop
res = []
for ele in test_str:
        res.append(test_str[K] + ele)
  
# printing result 
print("List after pairing : " + str(res)) 

chevron_right


Output :

The original string is : geeksforgeeks
List after pairing : ['sg', 'se', 'se', 'sk', 'ss', 'sf', 'so', 'sr', 'sg', 'se', 'se', 'sk', 'ss']

 

Method #2 : Using join() + zip() + cycle()
The combination of above functions can be used to perform this task. In this, we perform the task of joining using join(). The task of pairing with all is done with zip() + cycle().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Pair Kth character with each element
# Using join() + zip() + cycle()
from itertools import cycle
  
# initializing string
test_str = "geeksforgeeks"
  
# printing original string
print("The original string is : " + test_str)
  
# initializing K 
K = 4
  
# Pair Kth character with each element
# Using join() + zip() + cycle()
res = list(map(''.join, zip(cycle(test_str[K]), test_str)))
  
# printing result 
print("List after pairing : " + str(res)) 

chevron_right


Output :

The original string is : geeksforgeeks
List after pairing : ['sg', 'se', 'se', 'sk', 'ss', 'sf', 'so', 'sr', 'sg', 'se', 'se', 'sk', 'ss']



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.