如何在python中的纯文本中添加后缀 [英] How to add suffix to a plain text in python

查看:30
本文介绍了如何在python中的纯文本中添加后缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下要通过邮件发送的文本.我必须将其转换为html,因此必须在每个行分隔符中添加
.

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'

推荐答案

您可能正在寻找替换换行符

>>> 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>

或者,您可以使用< pre> (预格式化的文本)按原样写出文本!(尽管对于代码块来说确实更多,并且可能不适用于其他文本)

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>

PacketLoss 所述,如果您只需要替换一个琐碎的字符/子字符串,则使用 .replace()字符串方法是可以的,并且可能会更好/更清晰!

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!

这篇关于如何在python中的纯文本中添加后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆