Skip to content

Fix #12408 Bug fix for empty strings in join.py #12411

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 7 additions & 15 deletions strings/join.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
...
Expand All @@ -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__":
Expand Down
Loading