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

新手上路,请多包涵

问题:实现一个名为 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)

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

原文由 Destiny Brown 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 839
2 个回答

您可以通过 re.sub 函数来实现。

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

print(stripComments("""#foo bar
bar foo
# buz"""))

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

原文由 Avinash Raj 发布,翻译遵循 CC BY-SA 3.0 许可协议

供我以后参考。

 def remove_comments(lines: list[str]) -> list[str]:
    new_lines = []
    for line in lines:
        if line.startswith("#"):  # Deal with comment as the first character
            continue

        line = line.split(" #")[0]
        if line.strip() != "":
            new_lines.append(line)

    return new_lines

print(remove_comments("Hello #World!\n\nI have a question # that #".split('\n')))
>>> ['Hello', 'I have a question']

此实现的好处是不需要 re 模块并且易于理解。它还会删除预先存在的空白行,这对我的用例很有用。

原文由 WyattBlue 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进