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?
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']
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)
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.
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?
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']
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)
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.