diff --git a/strings/join.py b/strings/join.py index 5c02f65a20ce..737cef38eae2 100644 --- a/strings/join.py +++ b/strings/join.py @@ -8,25 +8,22 @@ def join(separator: str, separated: list[str]) -> str: Joins a list of strings using a separator and returns the result. - :param separator: Separator to be used - for joining the strings. + :param separator: Separator to be used for joining the strings. :param separated: List of strings to be joined. :return: Joined string with the specified separator. Examples: - + >>> join(",", ["", "", ""]) + ',,' >>> join("", ["a", "b", "c", "d"]) 'abcd' >>> join("#", ["a", "b", "c", "d"]) 'a#b#c#d' - >>> join("#", "a") - 'a' >>> join(" ", ["You", "are", "amazing!"]) 'You are amazing!' - This example should raise an - exception for non-string elements: + This example should raise an exception for non-string elements: >>> join("#", ["a", "b", "c", 1]) Traceback (most recent call last): ... @@ -37,15 +34,10 @@ def join(separator: str, separated: list[str]) -> str: 'apple-banana-cherry' """ - joined = "" - for word_or_phrase in separated: - if not isinstance(word_or_phrase, str): - raise Exception("join() accepts only strings") - joined += word_or_phrase + separator + if not all(isinstance(word_or_phrase, str) for word_or_phrase in separated): + raise Exception("join() accepts only strings") - # Remove the trailing separator - # by stripping it from the result - return joined.strip(separator) + return separator.join(separated) if __name__ == "__main__":