How to add suffix to a plain text in python

情到浓时终转凉″ 提交于 2021-01-28 11:42:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!