Python – Removing multiline comments from a list

Question:

I have a list of data:

data = ['value', '"""', 'Comment 1st row', 'Comment 2nd row', 'Comment 3rd row', '"""', 'another value']

I would like to remove the whole comment from the list, including docstrings. Also not just once, but everytime a comment appears.

Could someone help?

Asked By: Peter HrnĨírik

||

Answers:

You can use a simple loop with a flag that alternates every time a """ is found:

data = ['value', '"""', 'Comment 1st row', 'Comment 2nd row',
        'Comment 3rd row', '"""', 'another value']

flag = True
out = []
for v in data:
    if v == '"""':
        flag = not flag  # invert the flag's boolean value
        continue         # we have a comment, skip to the next step
    if flag:             # if flag is True, add the item
        out.append(v)

print(out)

output:

['value', 'another value']

Example run on data = data * 5 to mimic multiple comments:

['value', 'another value', 'value', 'another value',
 'value', 'another value', 'value', 'another value',
 'value', 'another value']
Answered By: mozway

Try this:

data = ['value', '"""', 'Comment 1st row', 'Comment 2nd row', 'Comment 3rd row', '"""', 'another value']

newData = []

comment = False

for word in data:
    if word == '"""':
        comment = not comment
    elif not comment:
        newData.append(word)

print(newData)
Answered By: bbbbbbbbb

You can do with re,

import re
sp_chr = '$'
list(filter(None, re.sub(r'""".*"""', '', sp_chr.join(data)).split(sp_chr)))

Output:

['value', 'another value']

$ is a unique character used to separate the elements in the list. You have the freedom to choose any values there.

Answered By: Rahul K P
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.