如何从字符串中删除“#”注释?

Des*_*own 7 string comments python-3.x

问题:实现一个名为 stripComments(code) 的 Python 函数,其中 code 是一个参数,它采用包含 Python 代码的字符串。函数 stripComments() 返回删除所有注释的代码。

我有:

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)
Run Code Online (Sandbox Code Playgroud)

我不确定如何具体告诉 python 搜索字符串的每一行,并在找到主题标签时删除该行的其余部分。请帮忙。:(

Avi*_*Raj 3

您可以通过re.sub功能来实现这一点。

import re
def stripComments(code):
    code = str(code)
    return re.sub(r'(?m)^ *#.*\n?', '', code)

print(stripComments("""#foo bar
bar foo
# buz"""))
Run Code Online (Sandbox Code Playgroud)

(?m)启用多行模式。^断言我们正处于起步阶段。<space>*#匹配开头的字符#(前面有或没有空格)。.*匹配除换行符之外的所有以下字符。用空字符串替换那些匹配的字符将为您提供删除了注释行的字符串。

  • 请注意,这不会删除活动代码行末尾的注释。 (3认同)
  • 请注意,如果一行代码包含“#”作为代码的一部分,即使您通过从正则表达式字符串中删除“^”将其修复为在活动代码行之后工作,这也不起作用 (3认同)