问题:实现一个名为stripComments(code)的Python函数,其中code是一个参数,该参数采用包含Python代码的字符串。函数stripComments()返回删除了所有注释的代码。
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.
我有:
def stripComments(code): code = str(code) for line in code: comments = [word[1:] for word in code.split() if word[0] == '#'] del(comments) stripComments(code)我不确定如何具体告诉python在字符串的每一行中进行搜索以及何时找到井号标签,以删除该行的其余部分。 请帮助。 :(
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. :(
推荐答案您可以通过 re.sub 函数实现此目的。
You could achieve this through re.sub function.
import re def stripComments(code): code = str(code) return re.sub(r'(?m)^ *#.*\n?', '', code) print(stripComments("""#foo bar bar foo # buz"""))(?m )启用多行模式。 ^ 断言我们才是开始。< space> *#开头匹配字符#,。* 匹配以下所有字符除了换行符外,用空字符串替换那些匹配的字符将为您提供删除注释行的字符串。
(?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.
更多推荐
如何从字符串中删除“#”注释?
发布评论