MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / join

Function join

strings/join.py:6–68  ·  view source on GitHub ↗

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: >>> join("

(separator: str, separated: list[str])

Source from the content-addressed store, hash-verified

4
5
6def join(separator: str, separated: list[str]) -> str:
7 """
8 Joins a list of strings using a separator
9 and returns the result.
10
11 :param separator: Separator to be used
12 for joining the strings.
13 :param separated: List of strings to be joined.
14
15 :return: Joined string with the specified separator.
16
17 Examples:
18
19 >>> join("", ["a", "b", "c", "d"])
20 'abcd'
21 >>> join("#", ["a", "b", "c", "d"])
22 'a#b#c#d'
23 >>> join("#", "a")
24 'a'
25 >>> join(" ", ["You", "are", "amazing!"])
26 'You are amazing!'
27 >>> join(",", ["", "", ""])
28 ',,'
29
30 This example should raise an
31 exception for non-string elements:
32 >>> join("#", ["a", "b", "c", 1])
33 Traceback (most recent call last):
34 ...
35 Exception: join() accepts only strings
36
37 Additional test case with a different separator:
38 >>> join("-", ["apple", "banana", "cherry"])
39 'apple-banana-cherry'
40 """
41
42 # Check that all elements are strings
43 for word_or_phrase in separated:
44 # If the element is not a string, raise an exception
45 if not isinstance(word_or_phrase, str):
46 raise Exception("join() accepts only strings")
47
48 joined: str = ""
49 """
50 The last element of the list is not followed by the separator.
51 So, we need to iterate through the list and join each element
52 with the separator except the last element.
53 """
54 last_index: int = len(separated) - 1
55 """
56 Iterate through the list and join each element with the separator.
57 Except the last element, all other elements are followed by the separator.
58 """
59 for word_or_phrase in separated[:last_index]:
60 # join the element with the separator.
61 joined += word_or_phrase + separator
62
63 # If the list is not empty, join the last element.

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected