去掉html 每一行的收尾空白
时间: 2023-05-21 09:03:15 浏览: 66
可以使用正则表达式来去掉每一行的收尾空白,具体代码如下:
```python
import re
html = """
<html>
<head>
<title>Test Page</title>
</head>
<body>
<p> This is a test page. </p>
</body>
</html>
"""
# 去掉每一行的收尾空白
html = re.sub(r"(?m)^\s+", "", html)
html = re.sub(r"(?m)\s+$", "", html)
print(html)
```
输出结果如下:
```
<html>
<head>
<title>Test Page</title>
</head>
<body>
<p> This is a test page. </p>
</body>
</html>
```
相关问题
去掉html 收尾空白
以下是Python的示例代码,它可以去除HTML标记的开头和结尾的空白:
```python
import re
def strip_html_tags(text):
"""
去除HTML标记的开头和结尾的空白
"""
# 去除HTML标记
text = re.sub('<[^<]+?>', '', text)
# 去除开头和结尾的空白
text = text.strip()
return text
```
这个函数使用正则表达式`<[^<]+?>`来匹配HTML标记,并使用`re.sub()`函数将它们替换为空字符串。然后,使用`strip()`函数去除开头和结尾的空白。
正则去掉html 收尾空白
可以使用以下正则表达式来去掉HTML标签和收尾空白:
```python
import re
html = "<p>这是一段 <b>HTML</b> 文本。</p> "
cleaned = re.sub(r'<[^>]*>', '', html).strip()
print(cleaned)
```
输出:
```
这是一段 HTML 文本。
```
解释:
- `<[^>]*>`:匹配任何以 `<` 开始、以 `>` 结束的字符序列,这里表示匹配所有HTML标签。
- `re.sub()` 函数用来替换匹配的文本,第一个参数是正则表达式,第二个参数是替换的文本(这里是空字符串)。
- `strip()` 函数用来去掉字符串两端的空白。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)