GH avatar 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!

go back Advanced level
Bitecoin 4X

51 out of 57 users completed this Bite.
Will you be Pythonista #52 to crack this Bite?
Resolution time: ~49 min. (avg. submissions of 5-240 min.)
Pythonistas rate this Bite 8.0 on a 1-10 difficulty scale.
» Up for a challenge? 💪

Buy Now Login and get coding
We use Python 3.7