如何从字符串中删除“#”注释? [英] How to remove '#' comments from a string?

查看:133
本文介绍了如何从字符串中删除“#”注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于如何从字符串中删除“#”注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆