Pybites Logo

Strip comments from python code

Level: Advanced (score: 4)

In this Bite you will strip off all comments from some Python source code. Complete strip_comments that takes some multiline code string and strip out:

  • Single line comments = lines that start with #.
  • PEP8-compliant inline comments, so code followed by 2 spaces, a #, a space and comment.
  • Multiline comments / docstrings ("""my\ncomment"""), which could be non indented (at the module level) or indented in a function/ method. You can assume these have always 3 double, not single, quotes.

Return a string of the code without comments.

So this code:

"""this is
my awesome script
"""
# importing modules
import re

def hello(name):
    """my function docstring"""
    return f'hello {name}'  # my inline comment

... would result in:

import re

def hello(name):
    return f'hello {name}'

Good luck and keep calm and code in Python!