问题
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:
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!
回答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>
来源:https://stackoverflow.com/questions/65801481/how-to-add-suffix-to-a-plain-text-in-python