Bite 179. Strip comments from Python code

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!

12 out of 14 users completed this Bite.
Will you be Pythonista #13 to crack this Bite?
It takes an average of ~47 minutes to solve this Bite (submissions 5-240 min).
Pythonistas rate this Bite 8.0 on a 1-10 difficulty scale.
» Up for a challenge? 💪

Login and get coding
We use Python 3.7