Skip to content

Commit 7723540

Browse files
committed
Fix the Join issue
1 parent 3b1b70b commit 7723540

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

Diff for: strings/join.py

+16-12
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,19 @@ def join(separator: str, separated: list[str]) -> str:
1818
1919
>>> join("", ["a", "b", "c", "d"])
2020
'abcd'
21+
2122
>>> join("#", ["a", "b", "c", "d"])
2223
'a#b#c#d'
23-
>>> join("#", "a")
24+
25+
Single-element list:
26+
>>> join("#", ["a"])
2427
'a'
28+
29+
Joining with space as a separator:
2530
>>> join(" ", ["You", "are", "amazing!"])
2631
'You are amazing!'
2732
28-
This example should raise an
29-
exception for non-string elements:
33+
This example should raise an exception for non-string elements:
3034
>>> join("#", ["a", "b", "c", 1])
3135
Traceback (most recent call last):
3236
...
@@ -35,17 +39,17 @@ def join(separator: str, separated: list[str]) -> str:
3539
Additional test case with a different separator:
3640
>>> join("-", ["apple", "banana", "cherry"])
3741
'apple-banana-cherry'
38-
"""
3942
40-
joined = ""
41-
for word_or_phrase in separated:
42-
if not isinstance(word_or_phrase, str):
43-
raise Exception("join() accepts only strings")
44-
joined += word_or_phrase + separator
43+
Handling a list with empty strings:
44+
>>> join(",", ["", "", ""])
45+
',,'
46+
"""
47+
# Ensure all elements in the list are strings
48+
if not all(isinstance(item, str) for item in separated):
49+
raise Exception("join() accepts only strings")
4550

46-
# Remove the trailing separator
47-
# by stripping it from the result
48-
return joined.strip(separator)
51+
# Use Python's built-in join method for simplicity and correctness
52+
return separator.join(separated)
4953

5054

5155
if __name__ == "__main__":

0 commit comments

Comments
 (0)