Search code examples
pythonstringpython-2.7string-parsingsplit

How to divide string like this into items in Python


Here is the string:

format db "this is string a", 0, 0Ah

And I am trying to split it into this:

format
db
"this is string a"
0
0Ah

Is there any way can do this in python 2.7?

Thank you!


Solution

  • Use shlex.split:

    s = 'format db "this is string a", 0, 0Ah'
    
    import shlex
    
    shlex.split(s)
    Out[18]: ['format', 'db', 'this is string a,', '0,', '0Ah']
    

    Your grammar is a little wonky with the trailing commas, but you can pretty safely rstrip that out:

    [x.rstrip(',') for x in shlex.split(s)]
    Out[20]: ['format', 'db', 'this is string a', '0', '0Ah']