1

I have the following text that I want to send by mail. I have to convert it to html, therefore to each line separator I have to add
.

How can I do it in such a way that it fits me? Here is my attempt.

text = """
Hi, my name is John,
Regards
"""

strString = map(lambda x: x + '<br>', text)
print(list(strString))
['\n<br>', 'H<br>', 'i<br>', ',<br>', ' <br>', 'm<br>', 'y<br>', ' <br>', 'n<br>', 'a<br>', 'm<br>', 'e<br>', ' <br>', 'i<br>', 's<br>', ' <br>', 'J<br>', 'o<br>', 'h<br>', 'n<br>', ',<br>', '\n<br>', 'R<br>', 'e<br>', 'g<br>', 'a<br>', 'r<br>', 'd<br>', 's<br>', '\n<br>']

Desired output
text = """
Hi, my name is John,<br>
Regards<br>
"""
text
'\nHi, my name is John,<br>\nRegards<br>\n'
Raymont
  • 283
  • 3
  • 16

2 Answers2

1

You're probably looking to replace newlines

>>> text = """
... Hi, my name is John,
... Regards
... """
>>> import re
>>> print(re.sub(r"\n", "<br>\n", text))
<br>
Hi, my name is John,<br>
Regards<br>

Alternatively, you can use <pre> (preformatted text) to write out the text as-is! (though it's really more for code blocks and probably not appropriate for other text)

<pre>
Hi, my name is John,
Regards
</pre>

As PacketLoss notes, if you only have a trivial character/substring to replace, using the .replace() method of strings is fine and may be better/clearer!

ti7
  • 16,375
  • 6
  • 40
  • 68
  • 1
    Just to note @Raymont for basic uses such as this, you should use `string.replace()` as there is no need to use `regex` here. https://stackoverflow.com/questions/5668947/use-pythons-string-replace-vs-re-sub – PacketLoss Jan 20 '21 at 00:45
1

If you want to replace all new lines \n with <br> you can simply use string.replace()

print(text.replace('\n', '<br>'))
#<br>Hi, my name is John,<br>Regards<br>

To keep the new lines, just modify your replacement value.

print(text.replace('\n', '<br>\n'))
<br>
Hi, my name is John,<br>
Regards<br>
PacketLoss
  • 5,561
  • 1
  • 9
  • 27