codio 3.34nusearch short string list code example

Example: python how to format a string with quotation marks to and array with split(" ")

def format_string_to_array(string):
    array = []
    array_item = ""
    is_quote = False
    i = 0
    while i < len(string):
        
        if string[i:i+1] == " ":
            # Character is a space
            if is_quote == True:
                # If quote, add character to array_string
                array_item += string[i]
            elif is_quote == False:
                # When word is finished
                if not array_item == "":
                    # If array does not equal nothing, append
                    array.append(array_item)
                    array_item = ""
        elif string[i:i+1] == "\"" or string[i:i+1] == "\'":
            # Character is a quote
            if is_quote == False:
                is_quote = True
            else:
                array.append(array_item)
                array_item = ""
                is_quote = False
        else:
            # Character is normal
            array_item += string[i]

        i += 1
    array.append(array_item)
    return array

a = "Hello \'single array item with spaces\' World!"
print(format_string_to_array(a))