Skip to content

Commit fb63afe

Browse files
committed
updated join.py
1 parent ae09865 commit fb63afe

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

strings/join.py

+29-7
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,37 @@ def join(separator: str, separated: list[str]) -> str:
1010
:return: A single string with elements joined by the separator.
1111
1212
: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")
1613
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+
"""
1834
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:
2244
result += separator
2345

2446
return result

0 commit comments

Comments
 (0)