Code for Splitting a String by Whitespace in Python-
my_string = "Hi, fam!"
# Split that only works when there are no consecutive separators
def split_string(my_string: str, seps: list):
items = []
i = 0
while i < len(my_string):
sub = next_word_or_separator(my_string, i, seps)
if sub[0] not in seps:
items.append(sub)
i += len(sub)
return items
split_string(my_string) # ["Hi,", "fam!"]
# A more robust, albeit much slower, implementation of split
def next_word_or_separator(text: str, position: int, separators: list):
test_separator = lambda x: text[x] in separators
end_index = position
is_separator = test_separator(position)
while end_index < len(text) and is_separator == test_separator(end_index):
end_index += 1
return text[position: end_index]
def split_string(my_string: str, seps: list):
items = []
i = 0
while i < len(my_string):
sub = next_word_or_separator(my_string, i, seps)
if sub[0] not in seps:
items.append(sub)
i += len(sub)
return items
split_string(my_string) # ["Hi,", "fam!"]
# The builtin split solution **preferred**
my_string.split() # ["Hi,", "fam!"]