Search code examples
pythonsplitquotes

Python split everything between ""s


How do you split everything between ""s in Python? Including the ""s itself? For example, I want to split something like print "HELLO" to just ['print '] because I split everything in the quotes, including the quotes itself.

Other examples:

1) print "Hello", "World!" => ['print ', ', ']

2) if "one" == "one": print "one is one" => ['if ', ' == ', ': print ']

Any help is appreciated.


Solution

  • Use re.split():

    In [3]: re.split('".*?"', 'print "HELLO"')
    Out[3]: ['print ', '']
    
    
    In [4]: re.split('".*?"', '"Goodbye", "Farewell", and "Amen"')
    Out[4]: ['', ', ', ', and ', '']
    

    Note the use of .*?, the non-greedy all-consuming pattern.