mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-01-18 08:17:01 +00:00
2d68bb50e5
* Fix split function to handle trailing delimiters correctly * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update split.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>
38 lines
937 B
Python
38 lines
937 B
Python
def split(string: str, separator: str = " ") -> list:
|
|
"""
|
|
Will split the string up into all the values separated by the separator
|
|
(defaults to spaces)
|
|
|
|
>>> 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', '']
|
|
"""
|
|
|
|
split_words = []
|
|
|
|
last_index = 0
|
|
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])
|
|
return split_words
|
|
|
|
|
|
if __name__ == "__main__":
|
|
from doctest import testmod
|
|
|
|
testmod()
|