You could achieve this through re.sub
function.
return re.sub(r'(?m)^ *#.*n?', '', code)
print(stripComments("""#foo bar
<code>import re
def stripComments(code):
code = str(code)
return re.sub(r'(?m)^ *#.*n?', '', code)
print(stripComments("""#foo bar
bar foo
# buz"""))
</code>
import re
def stripComments(code):
code = str(code)
return re.sub(r'(?m)^ *#.*n?', '', code)
print(stripComments("""#foo bar
bar foo
# buz"""))
(?m)
enables the multiline mode. ^
asserts that we are at the start. <space>*#
matches the character #
at the start with or without preceding spaces. .*
matches all the following characters except line breaks. Replacing those matched characters with empty string will give you the string with comment lines deleted.
How to remove ‘#’ comments from a string?
The problem:
Implement a Python function called stripComments(code) where code is a parameter that takes a string containing the Python code. The function stripComments() returns the code with all comments removed.
I have:
I’m not sure how to specifically tell python to search through each line of the string and when it finds a hashtag, to delete the rest of the line.
Please help. 🙁
1
You could achieve this through
re.sub
function.(?m)
enables the multiline mode.^
asserts that we are at the start.<space>*#
matches the character#
at the start with or without preceding spaces..*
matches all the following characters except line breaks. Replacing those matched characters with empty string will give you the string with comment lines deleted.2
For my future reference.
This implementation has benefit of not requiring the
re
module and being easy to understand. It also removes pre-existing blank lines, which is useful for my use case.1
1
1
Filed under: Kiến thức lập trình - @ 15:51
Thẻ: stringpython-3.xcomments