Python: how to replace html characters &lt; with < and &gt; with > in a Python list

Viewed 613

I have a reference list containing function names in this format:

list_1_ref = ['Name1<abc>' , 'Name2<abc>']

From another function I get a return list containing elements with html format:

list_2 = ['Name1&lt;abc&gt;' , 'Name2&lt;abc&gt;']

My code should now compare if an element from list_2 is contained in the first list:

for element in list2:
    if element in list_1_ref:
        # ...do something...

Unfortunately this does not work, I guess because of the html characters &lt; and &gt;. What is an efficient method so solve this? I thought of a replacement, but my Python skills are limited and I am not sure how to do this and if it is the most efficient way.

Thank you!

1 Answers

You could use html.unescape on your second list to compare the strings with the conversion applied:

import html


for html_element in list_2:
    element = html.unescape(html_element)
    if element in list_1_ref:
        # ...

How does the output of html.unescape look?

>>> html.unescape('Name1&lt;abc&gt;')
'Name1<abc>'
Related