Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Concatenate Strings in the Given Order
When you need to concatenate strings in a specific custom order, you can use simple iteration with index-based access. This technique allows you to rearrange and join string elements according to any desired sequence.
Basic Example
Below is a demonstration of concatenating strings in a custom order −
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)
The list is: ['pyt', 'fun', 'for', 'learning'] The result is: funpytlearningfor
How It Works
The process follows these steps:
A list of strings is defined:
["pyt", "fun", "for", "learning"]A sort order list
[1, 0, 3, 2]specifies the indices in desired sequenceAn empty string accumulates the concatenated result
Each index from sort_order accesses the corresponding string element
The accessed strings are appended in the specified order
Alternative Approaches
Using List Comprehension
words = ["hello", "world", "python", "rocks"]
order = [3, 1, 0, 2]
result = ''.join([words[i] for i in order])
print("Result:", result)
Result: rocksworldhellopython
Using join() with Generator
words = ["data", "science", "is", "amazing"]
order = [2, 3, 1, 0]
result = ''.join(words[i] for i in order)
print("Result:", result)
Result: isamazingsciencedata
Practical Example
Here's a real-world example of reordering date components −
date_parts = ["2024", "12", "25"]
# Convert from YYYY-MM-DD to DD-MM-YYYY format
order = [2, 1, 0]
separator = "-"
formatted_date = separator.join([date_parts[i] for i in order])
print("Original format:", "-".join(date_parts))
print("Reordered format:", formatted_date)
Original format: 2024-12-25 Reordered format: 25-12-2024
Conclusion
String concatenation in custom order is achieved by using an index list to specify the sequence. Use join() with list comprehension for cleaner, more efficient code when dealing with multiple strings.
