Skip to content

Commit e50c4d5

Browse files
authored
Update join.py
1 parent b22fab0 commit e50c4d5

File tree

1 file changed

+7
-17
lines changed

1 file changed

+7
-17
lines changed

strings/join.py

+7-17
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,27 @@
11
"""
22
Program to join a list of strings with a separator
33
"""
4-
5-
64
def join(separator: str, separated: list[str]) -> str:
75
"""
86
Joins a list of strings using a separator
97
and returns the result.
108
11-
:param separator: Separator to be used
12-
for joining the strings.
9+
:param separator: Separator to be used for joining the strings.
1310
:param separated: List of strings to be joined.
1411
1512
:return: Joined string with the specified separator.
1613
1714
Examples:
18-
15+
>>> join(",", ["", "", ""])
16+
',,'
1917
>>> join("", ["a", "b", "c", "d"])
2018
'abcd'
2119
>>> join("#", ["a", "b", "c", "d"])
2220
'a#b#c#d'
23-
>>> join("#", "a")
24-
'a'
2521
>>> join(" ", ["You", "are", "amazing!"])
2622
'You are amazing!'
2723
28-
This example should raise an
29-
exception for non-string elements:
24+
This example should raise an exception for non-string elements:
3025
>>> join("#", ["a", "b", "c", 1])
3126
Traceback (most recent call last):
3227
...
@@ -37,15 +32,10 @@ def join(separator: str, separated: list[str]) -> str:
3732
'apple-banana-cherry'
3833
"""
3934

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")
4537

46-
# Remove the trailing separator
47-
# by stripping it from the result
48-
return joined.strip(separator)
38+
return separator.join(separated)
4939

5040

5141
if __name__ == "__main__":

0 commit comments

Comments
 (0)