It does not show the \n breaks. this is what I see in a Python interpreter. And I want to convert it to HTML that will add in the line breaks. I was looking around and didn't see any libraries that do this out of the box. I was thinking BeautifulSoup, but wasn't quite sure.
6,394 6 6 gold badges 30 30 silver badges 74 74 bronze badges asked Mar 9, 2019 at 16:07 dropWizard dropWizard 3,508 9 9 gold badges 68 68 silver badges 90 90 bronze badgesIf you have a String that you have readed it from a file you can just replace \n to
, which is a line break in html, by doing:
my_string.replace('\n', '
')
answered Mar 9, 2019 at 16:12
Pablo Martinez Pablo Martinez
459 3 3 silver badges 7 7 bronze badges
You can use the python replace(. ) method to replace all line breaks with the html version
and possibly surround the string in a paragraph tag
.
. Let's say the name of the variable with the text is text :html = "" + text.replace("\n", "
") + "
"
answered Mar 9, 2019 at 16:30
Omari Celestine Omari Celestine
1,435 1 1 gold badge 13 13 silver badges 21 21 bronze badges
searching for this answer in found this, witch is likely better because it encodes all characters, at least for python 3 Python – Convert HTML Characters To Strings
# import html import html # Create Text text = 'Γeeks for Γeeks' # It Converts given text To String print(html.unescape(text)) # It Converts given text to HTML Entities print(html.escape(text))
answered Sep 27, 2022 at 8:21
Cedric lacrambe Cedric lacrambe
51 1 1 silver badge 1 1 bronze badge
You can use HTML tag.
html = '' + my_string '
' His this is a sample String
You don't need to care about \n or
.
If you want paragraphs (
tags) instead of breaks (
tags), you can use a regex:
import re def text_to_html_paragraphs(text): # First, replace multiple newlines with a single newline, # so you don't get empty paragraphs text = re.sub(r'\n\s*\n', '\n', text) # Split the text into lines lines = text.split('\n') # Wrap each line in a tag and join them return ''.join(f'
\n' for line in lines) text = """His this is a sample String""" html_paragraphs = text_to_html_paragraphs(text) print(html_paragraphs)
Result:
is
a sample
String