Skip to content
Related Articles

Related Articles

Improve Article

Python – Concatenate Strings in the Given Order

  • Last Updated : 11 Oct, 2020

Given a String List and order list, perform string concatenation in specific order.

Input : test_list = [“best”, “Gfg”, “for”, “is”], sort_order = [1, 3, 0, 2] 
Output : Gfgisbestfor 
Explanation : Combined as per order of indices.
Input : test_list = [“best”, “Gfg”], sort_order = [1, 0] 
Output : Gfgbest 
Explanation : Combined as per order of indices. 
 

Method #1 : Using loop

In this, we iterate order elements in loop, and perform concatenation of strings of similar index in similar order.

Python3




# Python3 code to demonstrate working of 
# Concatenate Strings in Order
# Using loop
  
# initializing list
test_list = ["best", "Gfg", "for", "is", "geeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing join order 
sort_order = [1, 3, 0, 2, 4]
  
res = ''
for ordr in sort_order:
      
    # concatenating by order 
    res += test_list[ordr]
  
# printing result 
print("Ordered concatenation : " + str(res))
Output



The original list is : ['best', 'Gfg', 'for', 'is', 'geeks']
Ordered concatenation : Gfgisbestforgeeks

Method #2 : Using join() + list comprehension

In this, we perform task of concatenation using join(), list comprehension is used for iteration of order.

Python3




# Python3 code to demonstrate working of 
# Concatenate Strings in Order
# Using join() + list comprehension
  
# initializing list
test_list = ["best", "Gfg", "for", "is", "geeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing join order 
sort_order = [1, 3, 0, 2, 4]
  
# join() performs concatenation
res = ''.join([test_list[ordr] for ordr in sort_order])
  
# printing result 
print("Ordered concatenation : " + str(res))

 
 

Output
The original list is : ['best', 'Gfg', 'for', 'is', 'geeks']
Ordered concatenation : Gfgisbestforgeeks

 

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :