splitting nested quotes and commas without regular expressions

Viewed 99

When I run my code it seems to have a bug, the code helps me split but keep comma but it should keep a quote if two are linked together. It seems to have three quotes linked together

input

Result = parseCSV('""')
print(Result)

expected output

['"']

actual output

['']

code:

def parseCSV(string):

    results = []
    current = ''
    is_quoted_right_now = False
    in_quotes = False


    for i in range(0, len(string)):
        currentletter = string[i]

        if currentletter == '"':
            if is_quoted_right_now == True:
                if in_quotes == True:
                    current = current + currentletter
                    in_quotes = False 
                else:
                    in_quotes = True

            else:
                is_quoted_right_now = True
                in_quotes = False

        else:

            shouldCheck  = False

            if is_quoted_right_now == True:

                if in_quotes == True:
                    is_quoted_right_now = False
                    in_quotes = False

                    shouldCheck = True

                else:
                    current = current + currentletter

            else:
                shouldCheck = True

            if shouldCheck == True:
                if currentletter == ',':
                    results.append(current)
                    current = ''

                else:
                    current = current +  currentletter

    results.append(current)
    return results

here's a few tests and results:

Result = parseCSV('","')
print(Result)
#result = [',']

Result = parseCSV('"""')
print(Result)
#result = ["]

Result = parseCSV('hi,i,am,splitting')
print(Result)
#result = ['hi','i','am','splitting']

Result = parseCSV('"hi,I,am,not,splitting"')
print(Result)
#result = ['hi,I,am,not,splitting']

Result = parseCSV('abc, """')
print(Result)
#result = ['abc', '"']

Result = parseCSV('abc, ""')
print(Result)
#result = ['abc','']
#wanted result = ['abc','"']

As you can see, there is just one problem, my dad says I have to use pure python with no modules so can anyone help without using things like regex

Thanks!!

I would really like for someone to post a sample code, thanks!!

0 Answers
Related