2021-10-18 13:35:35 +00:00
|
|
|
"""
|
2023-10-17 06:36:12 +00:00
|
|
|
Program to join a list of strings with a separator
|
2021-10-18 13:35:35 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
2021-10-22 17:14:08 +00:00
|
|
|
def join(separator: str, separated: list[str]) -> str:
|
2021-10-18 13:35:35 +00:00
|
|
|
"""
|
2023-10-17 06:36:12 +00:00
|
|
|
Joins a list of strings using a separator
|
|
|
|
and returns the result.
|
|
|
|
|
|
|
|
:param separator: Separator to be used
|
|
|
|
for joining the strings.
|
|
|
|
:param separated: List of strings to be joined.
|
|
|
|
|
|
|
|
:return: Joined string with the specified separator.
|
|
|
|
|
|
|
|
Examples:
|
|
|
|
|
2021-10-18 13:35:35 +00:00
|
|
|
>>> join("", ["a", "b", "c", "d"])
|
|
|
|
'abcd'
|
|
|
|
>>> join("#", ["a", "b", "c", "d"])
|
|
|
|
'a#b#c#d'
|
|
|
|
>>> join("#", "a")
|
|
|
|
'a'
|
|
|
|
>>> join(" ", ["You", "are", "amazing!"])
|
|
|
|
'You are amazing!'
|
2023-10-17 06:36:12 +00:00
|
|
|
|
|
|
|
This example should raise an
|
|
|
|
exception for non-string elements:
|
2021-10-18 13:35:35 +00:00
|
|
|
>>> join("#", ["a", "b", "c", 1])
|
|
|
|
Traceback (most recent call last):
|
2022-10-27 17:42:30 +00:00
|
|
|
...
|
2023-10-17 06:36:12 +00:00
|
|
|
Exception: join() accepts only strings
|
|
|
|
|
|
|
|
Additional test case with a different separator:
|
|
|
|
>>> join("-", ["apple", "banana", "cherry"])
|
|
|
|
'apple-banana-cherry'
|
2021-10-18 13:35:35 +00:00
|
|
|
"""
|
2023-10-17 06:36:12 +00:00
|
|
|
|
2021-10-18 13:35:35 +00:00
|
|
|
joined = ""
|
|
|
|
for word_or_phrase in separated:
|
|
|
|
if not isinstance(word_or_phrase, str):
|
2023-10-17 06:36:12 +00:00
|
|
|
raise Exception("join() accepts only strings")
|
2021-10-18 13:35:35 +00:00
|
|
|
joined += word_or_phrase + separator
|
2023-10-17 06:36:12 +00:00
|
|
|
|
|
|
|
# Remove the trailing separator
|
|
|
|
# by stripping it from the result
|
2021-10-18 13:35:35 +00:00
|
|
|
return joined.strip(separator)
|
|
|
|
|
|
|
|
|
2021-10-22 17:14:08 +00:00
|
|
|
if __name__ == "__main__":
|
2021-10-18 13:35:35 +00:00
|
|
|
from doctest import testmod
|
|
|
|
|
|
|
|
testmod()
|