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'
1
  • Are you wanting to keep or remove the \n? Commented Jan 20, 2021 at 0:32

2 Answers 2

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Just to note @Raymont for basic uses such as this, you should use string.replace() as there is no need to use regex here. stackoverflow.com/questions/5668947/…
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.