If the element starts with -, I want to try to add li tags. My ultimate goal to achieve something like this
lst = ['Para 1', '-list 01', 'para 2', '-list 2', '-list 3', 'para 3', 'para 4']
I want to achieve
<!-- wp:paragraph --><p>Para 1</p><!-- /wp:paragraph --><!-- wp:list --><ul><li>list 01</li></ul><!-- /wp:list --><!-- wp:paragraph --><p>para 2</p><!-- /wp:paragraph --><!-- wp:list --><ul><li>list 2</li><li>list 3</li></ul><!-- /wp:list --><!-- wp:paragraph --><p>para 3</p><!-- /wp:paragraph --><!-- wp:paragraph --><p>para 4</p><!-- /wp:paragraph -->
I am able to do it by these codes
lst = ['Para 1', '-list 01', 'para 2', '-list 2', '-list 3', 'para 3', 'para 4']
prfix_p = '<!-- wp:paragraph --><p>'
suffix_p = '</p><!-- /wp:paragraph -->'
prefix_li = '<li>'
suffix_li = '</li>'
ul_list_pre = '<!-- wp:list --><ul>'
ul_list_suff = '</ul><!-- /wp:list -->'
start = True
end = True
result = []
for i in lst:
if i.startswith('-'):
if not start:
result.append(prefix_li i[1:] suffix_li)
else:
result.append(ul_list_pre prefix_li i[1:] suffix_li)
start = False
else:
if not start:
result.append(ul_list_suff prfix_p i suffix_p)
start = True
else:
result.append(prfix_p i suffix_p)
print("".join(result))
But The same code won't work for this list
lst = ['Para 1', '-list 01']
I got this output
<!-- wp:paragraph --><p>Para 1</p><!-- /wp:paragraph --><!-- wp:list --><ul><li>list 01</li>
Missing </ul><!-- /wp:list -->
What did I do wrong? How Can I able to do this output
<!-- wp:paragraph --><p>Para 1</p><!-- /wp:paragraph --><!-- wp:list --><ul><li>list 01</li></ul><!-- /wp:list -->
Thanks
CodePudding user response:
Try itertools.groupby
:
from itertools import groupby
lst = ["Para 1", "-list 01", "para 2", "-list 2", "-list 3", "para 3", "para 4"]
out = ""
for k, g in groupby(lst, lambda s: s.startswith("-")):
if k:
out = "<!-- wp:list --><ul>"
for item in g:
out = f"<li>{item.strip('-')}</li>"
out = "</ul><!-- /wp:list -->"
else:
for item in g:
out = f"<!-- wp:paragraph --><p>{item}</p><!-- /wp:paragraph -->"
print(out)
Prints:
<!-- wp:paragraph --><p>Para 1</p><!-- /wp:paragraph --><!-- wp:list --><ul><li>list 01</li></ul><!-- /wp:list --><!-- wp:paragraph --><p>para 2</p><!-- /wp:paragraph --><!-- wp:list --><ul><li>list 2</li><li>list 3</li></ul><!-- /wp:list --><!-- wp:paragraph --><p>para 3</p><!-- /wp:paragraph --><!-- wp:paragraph --><p>para 4</p><!-- /wp:paragraph -->