How to remove '#' comments from a string?

后端 未结 2 1939
灰色年华
灰色年华 2021-01-06 14:57

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() re

相关标签:
2条回答
  • 2021-01-06 15:11

    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) 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.

    0 讨论(0)
  • 2021-01-06 15:20

    def remove_comments(filename1, filename2): """ Remove all comments beginning with # from filename1 and writes the result to filename2 """

    with open(filename1, 'r') as f:
        lines = f.readlines()
    
    with open(filename2, 'w') as f:
        for line in lines:
            # Keep the Shebang line
            if line[0:2] == "#!":
                f.writelines(line)
            # Also keep existing empty lines
            elif not line.strip():
                f.writelines(line)
            # But remove comments from other lines
            else:
                line = line.split('#')
                stripped_string = line[0].rstrip()
                # Write the line only if the comment was after the code.
                # Discard lines that only contain comments.
                if stripped_string:
                    f.writelines(stripped_string)
                    f.writelines('\n')
    
    0 讨论(0)
提交回复
热议问题