将文本区域输入转换为分段HTML

2024-04-29 15:18:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将用户输入的内容转换成一个带有<p>标记的输出,其中每个<p>都在替换新行。在

我正在尝试使用正则表达式,但无法使其正常工作。有人能纠正我的表情吗?在

String = "Hey, this is paragraph 1 \n and this is paragraph 2 \n and this will be paragraph 3"
Regex = r'(.+?)$'

结果就是Hey, this is paragraph 1 \n and this is paragraph 2 \n<p>and this will be paragraph 3</p>


Tags: and用户标记内容stringisbethis
3条回答

我不会为此使用正则表达式,因为您不需要它。看看这个:

text = "Hey, this is paragraph 1 \n and this is paragraph 2 \n and this will be paragraph 3"
html = ''
for line in text.split('\n'):
   html += '<p>' + line + '</p>'

print html

使其成为一行,因为越短越好,越清晰:

^{pr2}$

以上依赖于标识'\n'的答案不可靠。您需要使用.splitlines()。我没有足够的代表对选择的答案发表评论,当我编辑wiki时,有人只是恢复了它。所以能有更多代表的人来修理它。在

来自textarea的文本可以使用'\r\n'作为新行字符。在

>> "1\r\n2".split('\n') 
['1\r', '2']

单独使用“\r”在网页中是无效的,因此使用上述任何解决方案都会生成格式错误的网页。在

幸运的是python提供了一个函数来解决这个问题。可靠的答案是:

^{pr2}$

我会这样做:

s = "Hey, this is paragraph 1 \n and this is paragraph 2 \n and this will be paragraph 3"
"".join("<p>{0}</p>".format(row) for row in s.split('\n'))

你基本上把你的字符串分成一系列的行。然后用段落标记将每一行括起来。最后加入你们的队伍。在

相关问题 更多 >