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!

Login and get coding
go back Advanced level
Bitecoin 4X

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

We use Python 3.8