Skip to content

Instantly share code, notes, and snippets.

@shashi
Created March 20, 2014 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shashi/9673056 to your computer and use it in GitHub Desktop.
Save shashi/9673056 to your computer and use it in GitHub Desktop.
def remove_comments(line, pref="", ctx=None, escape=False):
if line == "": return pref
if ctx == "#" and line[0] != '\n':
return remove_comments(line[1:], pref, ctx)
if not ctx:
if line[0] == "#": return remove_comments(line[1:], pref, '#')
for c in ['"""', '"', "'"]:
if line.startswith(c):
# open context
return remove_comments(line[len(c):], pref + c, c)
if ctx and line.startswith(ctx):
# close context
if not escape:
return remove_comments(line[len(ctx):], pref + ctx, None)
# carry over context
if ctx != '"""' and line[0] == '\n':
ctx = None
return remove_comments(line[1:], pref + line[0], ctx,
not escape and line[0] == '\\')
tests = ['', '1; #a', '1; 1', '"" #"', '"a; #b"', '"a; #b" #c', '"a; # d \n b # c"', '"""a #c \n b #d""" #e', '"\\"" # test', '""#a\n""#b']
for t in tests:
print t, '->', remove_comments(t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment