Skip to content

Commit 00911f0

Browse files
author
Milad Khoshdel
committed
Refactor custom split implementation
1 parent 791deb4 commit 00911f0

1 file changed

Lines changed: 16 additions & 14 deletions

File tree

strings/split.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,36 @@
1-
def split(string: str, separator: str = " ") -> list:
1+
def split(string: str, separator: str = " ") -> list[str]:
22
"""
3-
Will split the string up into all the values separated by the separator
4-
(defaults to spaces)
3+
Split string into values separated by separator.
54
6-
>>> split("apple#banana#cherry#orange",separator='#')
5+
>>> split("apple#banana#cherry#orange", separator="#")
76
['apple', 'banana', 'cherry', 'orange']
87
98
>>> split("Hello there")
109
['Hello', 'there']
1110
12-
>>> split("11/22/63",separator = '/')
11+
>>> split("11/22/63", separator="/")
1312
['11', '22', '63']
1413
15-
>>> split("12:43:39",separator = ":")
14+
>>> split("12:43:39", separator=":")
1615
['12', '43', '39']
1716
18-
>>> split(";abbb;;c;", separator=';')
17+
>>> split(";abbb;;c;", separator=";")
1918
['', 'abbb', '', 'c', '']
2019
"""
2120

22-
split_words = []
21+
if len(separator) != 1:
22+
raise ValueError("separator must be exactly one character")
23+
24+
parts: list[str] = []
25+
start = 0
2326

24-
last_index = 0
2527
for index, char in enumerate(string):
2628
if char == separator:
27-
split_words.append(string[last_index:index])
28-
last_index = index + 1
29-
if index + 1 == len(string):
30-
split_words.append(string[last_index : index + 1])
31-
return split_words
29+
parts.append(string[start:index])
30+
start = index + 1
31+
32+
parts.append(string[start:])
33+
return parts
3234

3335

3436
if __name__ == "__main__":

0 commit comments

Comments
 (0)