How To Add Suffix To A Plain Text In Python
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?
Solution 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!
Solution 2:
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>
Post a Comment for "How To Add Suffix To A Plain Text In Python"