pythonfunctioncpython

How to write a function similar to split()


In my online PCAP learning course, this question is asked:
You already know how split() works. Now we want you to prove it. Your task is to write your own function, which behaves almost exactly like the original split() method, i.e.:

The skeleton given is:

def mysplit(strng):
    #
    # put your code here
    #


print(mysplit("To be or not to be, that is the question"))
print(mysplit("To be or not to be,that is the question"))
print(mysplit("   "))
print(mysplit(" abc "))
print(mysplit(""))

and the expected output is:

['To', 'be', 'or', 'not', 'to', 'be,', 'that', 'is', 'the', 'question']
['To', 'be', 'or', 'not', 'to', 'be,that', 'is', 'the', 'question']
[ ]
['abc']
[ ]

This is the code I came up with:

def mysplit(strng):
        A = ""
        B = []
        for i in strng:
                if i != " ":
                        A += i
                        
                else:
                        B.append(A)
                        A = ""

        return(B)
                        
print(mysplit("To be or not to be, that is the question"))
print(mysplit("To be or not to be,that is the question"))
print(mysplit("   "))
print(mysplit(" abc "))
print(mysplit(""))

BUT! My output is sooooo close, yet I'm not sure why is ("question") not in there, and why the supposed empty lists has [" "] in them...

['To', 'be', 'or', 'not', 'to', 'be,', 'that', 'is', 'the']
['To', 'be', 'or', 'not', 'to', 'be,that', 'is', 'the']
['', '', '']
['', 'abc']
[]

Any help is much appreciated!!


Solution

  • Two problems:

    1. You're not appending the last word to B, because you only append when you encounter a space, and there's no space at the end of the string. So you need to append the last word.
    2. When there are multiple spaces in a row, each one causes you to append the empty A to the result. You should only append A if it's not empty.
    def mysplit(strng):
        A = ""
        B = []
        for i in strng:
            if i != " ":
                A += i
            elif A != "":
                B.append(A)
                A = ""
        # Append last word
        if A != "":
            B.append(A)
    
        return(B)