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

MrJean1 MrJean1 at gmail.com
Thu Dec 4 17:31:48 EST 2008


Using rsplit('#', 1) works for lines *with* comments:

>>> 'this is a test'.rsplit('#', 1)
['this is a test']

>>> 'this is a test #with a comment'.rsplit('#', 1)
['this is a test ', 'with a comment']

>>> "this is a '#gnarlier' test #with a comment".rsplit('#', 1)
["this is a '#gnarlier' test ", 'with a comment']


But not if # occurs in lines without comments:

>>> "this is a '#gnarlier' test".rsplit('#', 1)
["this is a '", "gnarlier' test"]


/Jean Brouwers



On Dec 4, 7:50 am, Joe Strout <j... at strout.net> 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?
>
> Thanks,
> - Joe




More information about the Python-list mailing list