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

编程入门 行业动态 更新时间:2024-10-27 00:26:51
本文介绍了如何从字符串中删除“#”注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

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

本文发布于:2023-11-11 08:07:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577842.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   注释

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!