替换字符串中的段落标记

问题描述 投票:0回答:1

我有一个HTML字符串,我试图替换段落标记。我可以通过选择编辑>找到什么来手动完成:^p>用^s替换>替换所有。我的问题是如何在python中使用html字符串执行此操作?

sample_html_string = "<html>
                  <title>
                  Hello
                  </title>
                  </html>"

correct_html_string = "<html><title>Hello</title></html>"

这个问题不是简单地用re.sub解决的,因为我有一个更复杂的html字符串,其中包含li标签和p标签,我想要保持格式化。

python replace
1个回答
1
投票

你可以这样做:

>>> import re
>>> re.sub('\s+', '', sample_html_string)
'<html><title>Hello</title></html>"'

它将替换所有空格字符并完美适用于您的示例

如果你需要替换段落标记(你的意思是\n,对吗?)你可以使用内置的replace

>>> sample_html_string.replace('\n', '')
© www.soinside.com 2019 - 2024. All rights reserved.