[Python][Coding Pattern] Custom Join pattern
Custom Join
Purpose
The function combines all strings in a list using a custom separator, without using Python’s built-in `str.join()` at all.
Constraints
- Cannot use `str.join()` in any form
- Works with any separator string (e.g., "-", " ")
- Must not add separators at the start or end
- Must return an empty string for empty input
Step-by-Step Logic
1. Check if the list is empty
If there are no items to join, return an empty string immediately. This behavior is consistent with how `join()` would behave.
2. Prepare an empty string to build the result
You create a string variable to accumulate the final result. This will hold all parts, including separators, in the correct order.
3. Add the first item directly
The first item is added without a separator. This ensures that the result does not start with an extra separator.
4. Iterate through the rest of the list
Starting from the second element, you repeat the same action:
- First, add the separator
- Then, add the current string
This guarantees that separators only appear *between* elements.
5. Return the final result
The fully built string is returned after the loop ends.
Key Python Features Used
- Conditional check to handle empty input
- A loop with index-based access starting at the second element
- `+=` string concatenation for manual string construction
- Avoidance of `str.join()` as per the problem constraint
Comments
Post a Comment