@@ -10,15 +10,37 @@ def join(separator: str, separated: list[str]) -> str:
10
10
:return: A single string with elements joined by the separator.
11
11
12
12
:raises Exception: If any element in the list is not a string.
13
- """
14
- if not all (isinstance (word_or_phrase , str ) for word_or_phrase in separated ):
15
- raise Exception ("join() accepts only strings" )
16
13
17
- # Manually handle concatenation
14
+ Examples:
15
+ >>> join("", ["a", "b", "c", "d"])
16
+ 'abcd'
17
+ >>> join("#", ["a", "b", "c", "d"])
18
+ 'a#b#c#d'
19
+ >>> join("#", "a") # Single string instead of list
20
+ Traceback (most recent call last):
21
+ ...
22
+ Exception: join() accepts only strings
23
+ >>> join(" ", ["You", "are", "amazing!"])
24
+ 'You are amazing!'
25
+ >>> join("#", ["a", "b", "c", 1])
26
+ Traceback (most recent call last):
27
+ ...
28
+ Exception: join() accepts only strings
29
+ >>> join("-", ["apple", "banana", "cherry"])
30
+ 'apple-banana-cherry'
31
+ >>> join(",", ["", "", ""])
32
+ ',,'
33
+ """
18
34
result = ""
19
- for i , element in enumerate (separated ):
20
- result += element
21
- if i < len (separated ) - 1 : # Add separator only between elements
35
+ for i , word_or_phrase in enumerate (separated ):
36
+ # Check if the element is a string
37
+ if not isinstance (word_or_phrase , str ):
38
+ raise Exception ("join() accepts only strings" )
39
+
40
+ # Add the current word or phrase to the result
41
+ result += word_or_phrase
42
+ # Add the separator if it's not the last element
43
+ if i < len (separated ) - 1 :
22
44
result += separator
23
45
24
46
return result
0 commit comments