How to remove ‘#’ comments from a string?

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.

I have:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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)
</code>
<code>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) </code>
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)

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

1

You could achieve this through re.sub function.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import re
def stripComments(code):
code = str(code)
return re.sub(r'(?m)^ *#.*n?', '', code)
print(stripComments("""#foo bar
bar foo
# buz"""))
</code>
<code>import re def stripComments(code): code = str(code) return re.sub(r'(?m)^ *#.*n?', '', code) print(stripComments("""#foo bar bar foo # buz""")) </code>
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.

2

For my future reference.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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!nnI have a question # that #".split('n')))
>>> ['Hello', 'I have a question']
</code>
<code>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!nnI have a question # that #".split('n'))) >>> ['Hello', 'I have a question'] </code>
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!nnI have a question # that #".split('n')))
>>> ['Hello', 'I have a question']

This implementation has benefit of not requiring the re module and being easy to understand. It also removes pre-existing blank lines, which is useful for my use case.

1

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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')
</code>
<code>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') </code>
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')

1

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def removeComments(string: str):
"""Takes something like:
import math
math.pow(2,3) # 2 to the power of 3
and outputs:
import math
math.pow(2,3)
Maintains trailing whitespace
"""
isInComment=False
returnVal = ""
for char in string:
if char == '#':
isInComment=True
elif char == "n":
isInComment=False
if not isInComment:
returnVal+=char
return returnVal
</code>
<code>def removeComments(string: str): """Takes something like: import math math.pow(2,3) # 2 to the power of 3 and outputs: import math math.pow(2,3) Maintains trailing whitespace """ isInComment=False returnVal = "" for char in string: if char == '#': isInComment=True elif char == "n": isInComment=False if not isInComment: returnVal+=char return returnVal </code>
def removeComments(string: str):
    """Takes something like:

    import math

    math.pow(2,3) # 2 to the power of 3

    and outputs:

    import math
    
    math.pow(2,3) 

    Maintains trailing whitespace
    """
    isInComment=False
    returnVal = ""
    for char in string:
        if char == '#':
            isInComment=True
        elif char == "n":
            isInComment=False
        if not isInComment:
            returnVal+=char
    return returnVal

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật