[Tutor] Multi-line statements with comments

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 28 Dec 2001 17:41:44 -0800 (PST)


On Fri, 28 Dec 2001, Jim Angstadt wrote:


> However, the use of the continuation character does not permit one to
> have comments within the string.  In regular expressions, there is a
> way to disreguard whitespace within the RE, and add comments, which
> makes a lengthy expression more readable.  ( I'm referring to VERBOSE
> in python or x in perl. )
> 
> What is a good technique for commenting multi-line statements that are
> not REs?


We can cook up a simple function that allows us to do something like this:

###
comment_re = re.compile(r'#[^\n]*?\n')

def removeComments(s):
    return comment_re.sub('\n', s)    
###


Here's an example of how to use this function:

###
>>> removeComments('''this is # a test
... hello world ## foo!
... ''')
'this is \012hello world \012'
###



However, there's one big deficiency in the regular expression as it
stands: what happens if we give it soething like this?

###
s = removeComments("hello # why doesn't this comment disappear?")
print s
###


So there's definitely room to improve this.


Hope this helps!