[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

# Given a list of strings, return a single string with each item joined by a custom separator.

# Constraints:
# - No use of built-in str.join()
# - Separator can be any string
# - Return empty string for empty input

def custom_join(separator: str, items: list[str]) -> str:
    if not items:
        return ''

    target = ''
    target += items[0]
    for index in range(1, len(items)):
        target += separator
        target += items[index]

    return target

if __name__ == '__main__':
    assert custom_join("-", ["a", "b", "c"]) == "a-b-c"
    assert custom_join(" ", ["hello", "world"]) == "hello world"
    assert custom_join(",", []) == ""
    assert custom_join("|", ["one"]) == "one"

Comments