@@ -18,15 +18,19 @@ def join(separator: str, separated: list[str]) -> str:
18
18
19
19
>>> join("", ["a", "b", "c", "d"])
20
20
'abcd'
21
+
21
22
>>> join("#", ["a", "b", "c", "d"])
22
23
'a#b#c#d'
23
- >>> join("#", "a")
24
+
25
+ Single-element list:
26
+ >>> join("#", ["a"])
24
27
'a'
28
+
29
+ Joining with space as a separator:
25
30
>>> join(" ", ["You", "are", "amazing!"])
26
31
'You are amazing!'
27
32
28
- This example should raise an
29
- exception for non-string elements:
33
+ This example should raise an exception for non-string elements:
30
34
>>> join("#", ["a", "b", "c", 1])
31
35
Traceback (most recent call last):
32
36
...
@@ -35,17 +39,17 @@ def join(separator: str, separated: list[str]) -> str:
35
39
Additional test case with a different separator:
36
40
>>> join("-", ["apple", "banana", "cherry"])
37
41
'apple-banana-cherry'
38
- """
39
42
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" )
45
50
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 )
49
53
50
54
51
55
if __name__ == "__main__" :
0 commit comments