Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 972a5c1

Browse files
RajdeepBakolia2004pre-commit-ci[bot]MaximSmolskiy
authored
fixed the issue in strings/join.py (#12434)
* fixed the issue in strings/join.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update join.py * Update join.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
1 parent 2d68bb5 commit 972a5c1

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

‎strings/join.py

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ def join(separator: str, separated: list[str]) -> str:
2424
'a'
2525
>>> join(" ", ["You", "are", "amazing!"])
2626
'You are amazing!'
27+
>>> join(",", ["", "", ""])
28+
',,'
2729
2830
This example should raise an
2931
exception for non-string elements:
@@ -37,15 +39,33 @@ def join(separator: str, separated: list[str]) -> str:
3739
'apple-banana-cherry'
3840
"""
3941

40-
joined=""
42+
# Check that all elements are strings
4143
for word_or_phrase in separated:
44+
# If the element is not a string, raise an exception
4245
if not isinstance(word_or_phrase, str):
4346
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.
4461
joined += word_or_phrase + separator
4562

46-
# Remove the trailing separator
47-
# by stripping it from the result
48-
return joined.strip(separator)
63+
# If the list is not empty, join the last element.
64+
if separated != []:
65+
joined += separated[last_index]
66+
67+
# Return the joined string.
68+
return joined
4969

5070

5171
if __name__ == "__main__":

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /