|
1 | | -def split(string: str, separator: str = " ") -> list: |
| 1 | +def split(string: str, separator: str = " ") -> list[str]: |
2 | 2 | """ |
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. |
5 | 4 |
|
6 | | - >>> split("apple#banana#cherry#orange",separator='#') |
| 5 | + >>> split("apple#banana#cherry#orange", separator="#") |
7 | 6 | ['apple', 'banana', 'cherry', 'orange'] |
8 | 7 |
|
9 | 8 | >>> split("Hello there") |
10 | 9 | ['Hello', 'there'] |
11 | 10 |
|
12 | | - >>> split("11/22/63",separator = '/') |
| 11 | + >>> split("11/22/63", separator="/") |
13 | 12 | ['11', '22', '63'] |
14 | 13 |
|
15 | | - >>> split("12:43:39",separator = ":") |
| 14 | + >>> split("12:43:39", separator=":") |
16 | 15 | ['12', '43', '39'] |
17 | 16 |
|
18 | | - >>> split(";abbb;;c;", separator=';') |
| 17 | + >>> split(";abbb;;c;", separator=";") |
19 | 18 | ['', 'abbb', '', 'c', ''] |
20 | 19 | """ |
21 | 20 |
|
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 |
23 | 26 |
|
24 | | - last_index = 0 |
25 | 27 | for index, char in enumerate(string): |
26 | 28 | 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 |
32 | 34 |
|
33 | 35 |
|
34 | 36 | if __name__ == "__main__": |
|
0 commit comments