我有一个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
标签,我想要保持格式化。
你可以这样做:
>>> import re
>>> re.sub('\s+', '', sample_html_string)
'<html><title>Hello</title></html>"'
它将替换所有空格字符并完美适用于您的示例
如果你需要替换段落标记(你的意思是\n
,对吗?)你可以使用内置的replace
:
>>> sample_html_string.replace('\n', '')