You can use an HTML parser like BeautifulSoup to extract the text without tags (soup.text
), then strip the text of duplicate whitespaces/newlines etc:
input_str = '''
<li>Recognized by
<em>Microsoft</em> &
<em>Google, Inc.</em>, offices.</li>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(input_str,"html.parser")
text = " ".join(soup.text.split())
print(text)
Output:
Recognized by Microsoft & Google, Inc., offices.
Edit: based on your comments, in order to get a list of strings as an output (one for each li
tag, you can do:
input_str = '''<ul> <li>This is sentence one in a order</li> <li>This is sentence two in a order</li> <li>This is sentence <em>Three</em> in a order </li> <li>This is sentence <em>four</em> in a order </li> </ul>'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(input_str,"html.parser")
result = []
for li in soup.find_all('li'):
text = " ".join(li.text.split())
result.append(text)
print(result)
Output:
['This is sentence one in a order', 'This is sentence two in a order', 'This is sentence Three in a order', 'This is sentence four in a order']