Python で文字列から xa0 を削除する方法
Najwa Riyaz
2023年1月30日
Python
Python String
-
Unicodedata の
Normalize()関数を使用して、Python の文字列から\xa0を削除する -
文字列の
replace()関数を使用して、Python の文字列から\xa0を削除する -
Python の文字列から
\xa0を削除するには、stripを True に設定してBeautifulSoupライブラリのget_text()関数を使用する
この記事では、Python で文字列から\xa0 を削除するさまざまな方法を紹介します。
\xa0 Unicode は、プログラム内のハードスペースまたはノーブレークスペースを表します。 として表されます HTML で。
文字列から\xa0 を削除するのに役立つ Python 関数は次のとおりです。
unicodedataのnormalize()関数- 文字列の
replace()関数 stripがTrueとして有効になっているBeautifulSoupライブラリのget_text()関数。
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!
Python の文字列から\xa0 を削除するには、strip を True に設定して BeautifulSoup ライブラリの get_text() 関数を使用する
strip を True として有効にした BeautifulSoup 標準ライブラリの get_text() 関数を使用して、文字列から\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!
チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe