1
1
"""
2
2
Program to join a list of strings with a separator
3
3
"""
4
-
5
-
6
4
def join (separator : str , separated : list [str ]) -> str :
7
5
"""
8
6
Joins a list of strings using a separator
9
7
and returns the result.
10
8
11
- :param separator: Separator to be used
12
- for joining the strings.
9
+ :param separator: Separator to be used for joining the strings.
13
10
:param separated: List of strings to be joined.
14
11
15
12
:return: Joined string with the specified separator.
16
13
17
14
Examples:
18
-
15
+ >>> join(",", ["", "", ""])
16
+ ',,'
19
17
>>> join("", ["a", "b", "c", "d"])
20
18
'abcd'
21
19
>>> join("#", ["a", "b", "c", "d"])
22
20
'a#b#c#d'
23
- >>> join("#", "a")
24
- 'a'
25
21
>>> join(" ", ["You", "are", "amazing!"])
26
22
'You are amazing!'
27
23
28
- This example should raise an
29
- exception for non-string elements:
24
+ This example should raise an exception for non-string elements:
30
25
>>> join("#", ["a", "b", "c", 1])
31
26
Traceback (most recent call last):
32
27
...
@@ -37,15 +32,10 @@ def join(separator: str, separated: list[str]) -> str:
37
32
'apple-banana-cherry'
38
33
"""
39
34
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
35
+ if not all (isinstance (word_or_phrase , str ) for word_or_phrase in separated ):
36
+ raise Exception ("join() accepts only strings" )
45
37
46
- # Remove the trailing separator
47
- # by stripping it from the result
48
- return joined .strip (separator )
38
+ return separator .join (separated )
49
39
50
40
51
41
if __name__ == "__main__" :
0 commit comments