Skip to content

Commit 29db319

Browse files
authored
Enhance split function with separator validation
Added validation for separator length and improved docstring formatting.
1 parent 6c04620 commit 29db319

1 file changed

Lines changed: 13 additions & 10 deletions

File tree

strings/split.py

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,36 @@
11
def split(string: str, separator: str = " ") -> list:
22
"""
3-
Will split the string up into all the values separated by the separator
4-
(defaults to spaces)
5-
3+
Will split the string up into all the values separated by the separator (defaults to spaces)
64
>>> split("apple#banana#cherry#orange",separator='#')
75
['apple', 'banana', 'cherry', 'orange']
8-
96
>>> split("Hello there")
107
['Hello', 'there']
11-
128
>>> split("11/22/63",separator = '/')
139
['11', '22', '63']
14-
1510
>>> split("12:43:39",separator = ":")
1611
['12', '43', '39']
17-
1812
>>> split(";abbb;;c;", separator=';')
1913
['', 'abbb', '', 'c', '']
2014
"""
15+
if len(separator) != 1:
16+
raise ValueError("separator must be exactly one character long")
2117

22-
split_words = []
18+
# If the input string is empty, Python's split returns ['']
19+
if not string:
20+
return [""]
2321

22+
split_words = []
2423
last_index = 0
24+
25+
# Single-pass scan using string slicing for optimal memory and speed
2526
for index, char in enumerate(string):
2627
if char == separator:
2728
split_words.append(string[last_index:index])
2829
last_index = index + 1
29-
if index + 1 == len(string):
30-
split_words.append(string[last_index : index + 1])
30+
31+
# Append the remaining trailing substring after the last separator
32+
split_words.append(string[last_index:])
33+
3134
return split_words
3235

3336

0 commit comments

Comments
 (0)