Reputation: 119
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?
Upvotes: 1
Views: 312
Reputation: 4975
A counter-based approach. If the amount of """
is even then append (comments are balanced), instead increment the counter if odd (since comment hasn't finished).
res = []
c = 0
for char in data:
if char != '"""':
if not c % 2:
res.append(char)
else:
c += 1
print(res)
Upvotes: 0
Reputation: 260500
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']
Upvotes: 3
Reputation: 16081
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.
Upvotes: 1
Reputation:
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)
Upvotes: 1