One way to eliminate HTML tags from a string while preserving line breaks is to use a regular expression to replace all HTML tags with an empty string, and then replace all occurrences of "\n" (newline character) with "
" (HTML line break tag). Here is an example implementation in Python:
import re
def remove_html_tags(text):
# remove HTML tags
text = re.sub(r'<[^>]+>', '', text)
# replace newlines with HTML line break tag
text = text.replace('\n', '<br>')
return text
Example usage:
text = "<p>Hello, <b>world</b>!\nHow are you?</p>"
print(remove_html_tags(text))
# Output: Hello, world!<br>How are you?
Note that this method may not be perfect and might not work correctly for all HTML inputs. It's recommended to test it thoroughly and possibly adjust the regular expression to handle edge cases specific to your use case.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-06-16 11:00:00 +0000
Seen: 7 times
Last updated: Jun 12 '22
How can I set up Gunicorn with a Django Project?
Looking for a Python Module that finds Tags for a Text describing its Content
Need a Function in Python to remove entries less than 2 digits from an Array
How can I convert a Document in Python?
How can I program a Loop in Python?
How can I enable Python Code Highlighting in Askbot?