Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 13 additions & 10 deletions strings/split.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,36 @@
def split(string: str, separator: str = " ") -> list:
"""
Will split the string up into all the values separated by the separator
(defaults to spaces)

Will split the string up into all the values separated by the separator (defaults to spaces)

Check failure on line 3 in strings/split.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (E501)

strings/split.py:3:89: E501 Line too long (96 > 88)
>>> split("apple#banana#cherry#orange",separator='#')
['apple', 'banana', 'cherry', 'orange']

>>> split("Hello there")
['Hello', 'there']

>>> split("11/22/63",separator = '/')
['11', '22', '63']

>>> split("12:43:39",separator = ":")
['12', '43', '39']

>>> split(";abbb;;c;", separator=';')
['', 'abbb', '', 'c', '']
"""
if len(separator) != 1:
raise ValueError("separator must be exactly one character long")

split_words = []
# If the input string is empty, Python's split returns ['']
if not string:
return [""]

split_words = []
last_index = 0

# Single-pass scan using string slicing for optimal memory and speed
for index, char in enumerate(string):
if char == separator:
split_words.append(string[last_index:index])
last_index = index + 1
if index + 1 == len(string):
split_words.append(string[last_index : index + 1])

# Append the remaining trailing substring after the last separator
split_words.append(string[last_index:])

return split_words


Expand Down
Loading