Welcome, guest | Sign In | My Account | Store | Cart

There aren't many one-liner programs that exist, and that is probably a good thing. This recipe is designed to remove all comments from Python code where the comment is the only thing that is on a line of your program. This can be useful when just trying to get a summary of the code, especially if the comments are heavily used for documentation. Please take note of the program that this recipe has (listed below).

Python, 1 line
file('code.txt', 'w').write('\n'.join([line for line in file(raw_input('File? ')).read().splitlines() if not line.strip().startswith('#')]))

Do you have a multiline string that begins a newline with the '#' sign? If you answered yes, then you probably don't want to use this recipe. It will eat your string and possibly completely damage the correct logical operation of your program (assuming that it still runs). You have been warned ...

Created by Stephen Chappell on Tue, 7 Feb 2006 (PSF)
Python recipes (4591)
Stephen Chappell's recipes (233)

Required Modules

  • (none specified)

Other Information and Tasks