simplest way to strip a comment from the end of a line?

rdmurray at bitdance.com rdmurray at bitdance.com
Thu Dec 4 18:07:42 CET 2008


On Thu, 4 Dec 2008 at 08:50, Joe Strout wrote:
> I have lines in a config file which can end with a comment (delimited by # as 
> in Python), but which may also contain string literals (delimited by double 
> quotes).  A comment delimiter within a string literal doesn't count.  Is 
> there any easy way to strip off such a comment, or do I need to use a loop to 
> find each # and then count the quotation marks to its left?

     >>> from shlex import split
     >>> split("this is a test")
     ['this', 'is', 'a', 'test']
     >>> split("this is a test #with a comment")
     ['this', 'is', 'a', 'test', '#with', 'a', 'comment']
     >>> split("this is a test #with a comment", comments=True)
     ['this', 'is', 'a', 'test']
     >>> split("this is a '#gnarlier' test #with a comment", comments=True)
     ['this', 'is', 'a', '#gnarlier', 'test']

http://docs.python.org/library/shlex.html

--RDM



More information about the Python-list mailing list