Skip to content

Commit fa88559

Browse files
Create join.py (TheAlgorithms#5363)
* Create join.py Because we have a split.py * Update join.py * Update join.py * Update join.py * Update join.py * Update join.py * Update strings/join.py Co-authored-by: John Law <johnlaw.po@gmail.com> * Update join.py * Update join.py * Update join.py * Update join.py Co-authored-by: John Law <johnlaw.po@gmail.com>
1 parent 0935ab0 commit fa88559

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

strings/join.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
Program to join a list of strings with a given separator
3+
"""
4+
5+
6+
def join(separator: str, separated: list) -> str:
7+
"""
8+
>>> join("", ["a", "b", "c", "d"])
9+
'abcd'
10+
>>> join("#", ["a", "b", "c", "d"])
11+
'a#b#c#d'
12+
>>> join("#", "a")
13+
'a'
14+
>>> join(" ", ["You", "are", "amazing!"])
15+
'You are amazing!'
16+
>>> join("#", ["a", "b", "c", 1])
17+
Traceback (most recent call last):
18+
...
19+
Exception: join() accepts only strings to be joined
20+
"""
21+
joined = ""
22+
for word_or_phrase in separated:
23+
if not isinstance(word_or_phrase, str):
24+
raise Exception("join() accepts only strings to be joined")
25+
joined += word_or_phrase + separator
26+
return joined.strip(separator)
27+
28+
29+
if "__name__" == "__main__":
30+
from doctest import testmod
31+
32+
testmod()

0 commit comments

Comments
 (0)