PYTHON PROGRAMMING: REPLICATING THE SPLIT FUNCTION

John Okoye
2 min readMar 29, 2023

--

The Split function is a string manipulation function that can break down a string into smaller parts. The Split function does this based on the delimiter given and returns a list of all the substrings resulting from the breakdown.

The split function is defined this way:

split(delimiter, maxsplit)

Where maxsplit tells the function the maximum number of splits to make from the string, based on the delimiter.

# usage of the split function
a = "I love you"
# When it is used with no delimiter, the interpreter assumes the delimiter is a space " " :
print(a.split())
>>>['I', 'love', 'you']

The code box above shows how the split function works. For more on that, W3schools has a section dedicated to the split function.

Now, let us get into the meat of the topic. We will replicate the split function considering the following:

  1. The program has to read the string, character by character, and compare each character to the delimiter.
  2. If a character and the delimiter are the same, we break the string at that point.
  3. The split function returns a list of the split string. This means we have to concatenate(characters) and append(substrings) as the program progresses.
  4. A function split is declared with two parameters, word, and delimiter: the word is the string we want to split.
  5. An empty list word_list is created alongside an empty string, stringcat
  6. The for loop implements 1. The if/else statement implements 2 and part of 3.
  7. And the return statement returns the list word_list which contains the substring.
  8. The print statement at the end prints out the list.
"""
I want to replicate the split function
This function will use one delimeter

"""

# first point of call is to read through the string
def split(word = "", delimeter = ""):
word_list = []
stringcat = ""
for i in word:
if i == delimeter:
# when we find the delimeter, we pass the already read characters to a list
word_list.append(stringcat)
#we need to delete the items in strinngcat to create another string
stringcat = ""
# concatenate as we read
else:
stringcat = stringcat + i
word_list.append(stringcat)
return(word_list)

#function call in print statement

print(split("I,love,you,like,no,other ", " "))
>>>['I', 'love', 'you', 'like', 'no', 'other']

I have gone about this based on my thought process. It will be great to learn from your insights. Feel free to comment!

Thank you for reading!

Sign up to discover human stories that deepen your understanding of the world.

--

--

John Okoye
John Okoye

Written by John Okoye

Data, Engineering, and Writing Enthusiast

No responses yet

Write a response