Python – Concatenate Strings in the Given Order


When it is required to concatenate strings in a given order, a simple iteration is used.

Example

Below is a demonstration of the same −

my_list = ["pyt", "fun", "for", "learning"]

print("The list is :")

print(my_list)

sort_order = [1, 0, 3, 2]

my_result = ''
for element in sort_order:

   my_result += my_list[element]

print("The result is :")
print(my_result)

Output

The list is :
['pyt', 'fun', 'for', 'learning']
The result is :
funpytlearningfor

Explanation

  • A list is defined and displayed on the console.

  • Another list of integers is defined, which is the order of sorting.

  • An empty string is created.

  • The sort order list is iterated over, and the element being iterated over is used as index to access elements from the string list.

  • This is appended to the empty string.

  • This is the output that is displayed on the console.

Updated on: 08-Sep-2021

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements