Skip to content

fixed the issue in strings/join.py #12434

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

Merged
merged 4 commits into from
Dec 29, 2024
Merged
Changes from 3 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
44 changes: 36 additions & 8 deletions strings/join.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ def join(separator: str, separated: list[str]) -> str:
'a'
>>> join(" ", ["You", "are", "amazing!"])
'You are amazing!'
>>> join(",", ["", "", ""])
',,'

This example should raise an
exception for non-string elements:
Expand All @@ -37,15 +39,41 @@ 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):
joined: str = ""
"""
The last element of the list is not followed by the separator.
So, we need to iterate through the list and join each element
with the separator except the last element.
"""
last_index: int = len(separated) - 1
"""
Iterate through the list and join each element with the separator.
Except the last element, all other elements are followed by the separator.
"""
for index in range(last_index):
"""
If the element is not a string, raise an exception.
"""
if not isinstance(separated[index], str):
raise Exception("join() accepts only strings")
joined += word_or_phrase + separator

# Remove the trailing separator
# by stripping it from the result
return joined.strip(separator)
"""
join the element with the separator.
"""
joined += separated[index] + separator
"""
If the list is not empty, join the last element.
"""
if separated != []:
"""
If the last element is not a string, raise an exception.
"""
if not isinstance(separated[len(separated) - 1], str):
raise Exception("join() accepts only strings")
joined += separated[len(separated) - 1]
"""
RETURN the joined string.
"""
return joined


if __name__ == "__main__":
Expand Down
Loading