在 Python 中从字符串中删除 xa0 的方法
本文介绍了在 Python 中从字符串中删除 \xa0
的不同方法。
\xa0
Unicode 代表程序中的硬空间或不间断空间。它表示为
在 HTML 中。
可以帮助从字符串中删除 \xa0
的 Python 函数如下。
unicodedata
的normalize()
函数- 字符串的
replace()
函数 BeautifulSoup
库的get_text()
函数将strip
’ 设为True
。
使用 Unicodedata 的 Normalize()
函数从 Python 中的字符串中删除 \xa0
你可以使用 unicodedata
标准库的 unicodedata
normalize()
函数从字符串中删除 \xa0
。
normalize()
函数使用如下。
unicodedata.normalize("NFKD", string_to_normalize)
这里,NFKD 表示 normal form KD
。它将所有兼容字符替换为其等效字符。
下面的示例程序说明了这一点。
import unicodedata
str_hard_space='17\xa0kg on 23rd\xa0June 2021'
print (str_hard_space)
xa=u'\xa0'
if xa in str_hard_space:
print("xa0 is Found!")
else:
print("xa0 is not Found!")
new_str = unicodedata.normalize("NFKD", str_hard_space)
print (new_str)
if xa in new_str:
print("xa0 is Found!")
else:
print("xa0 is not Found!")
输出:
17 kg on 23rd June 2021
xa0 is Found!
17 kg on 23rd June 2021
xa0 is not Found!
使用字符串的 replace()
函数从 Python 中的字符串中删除 \xa0
你可以使用字符串的 replace()
函数从字符串中删除 \xa0
。
replace()
函数的用法如下。
str_hard_space.replace(u'\xa0', u' ')
下面的例子说明了这一点。
str_hard_space='16\xa0kg on 24th\xa0June 2021'
print (str_hard_space)
xa=u'\xa0'
if xa in str_hard_space:
print("xa0 Found!")
else:
print("xa0 not Found!")
new_str = str_hard_space.replace(u'\xa0', u' ')
print (new_str)
if xa in new_str:
print("xa0 Found!")
else:
print("xa0 not Found!")
输出:
16 kg on 24th June 2021
xa0 Found!
16 kg on 24th June 2021
xa0 not Found!
使用 BeautifulSoup
库的 get_text()
函数将 strip
设为 True
从 Python 中的字符串中删除 \xa0
你可以使用 BeautifulSoup
标准库的 get_text()
函数和 strip
启用为 True
从字符串中删除 \xa0
。
get_text()
函数的用法如下。
clean_html = BeautifulSoup(input_html, "lxml").get_text(strip=True)
下面的例子说明了这一点。
from bs4 import BeautifulSoup
html = 'This is a test message, Hello This is a test message, Hello\xa0here'
print (html)
clean_text = BeautifulSoup(html, "lxml").get_text(strip=True)
print(clean_text)
输出:
Hello, This is a test message, Welcome to this website!
Hello, This is a test message, Welcome to this website!
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串