在 Python 中刪除字串中的特殊字元
Muhammad Waiz Khan
2023年1月30日
Python
Python String
-
在 Python 中使用
str.isalnum()方法從字串中刪除特殊字元 -
在 Python 中使用
filter(str.isalnum, string)方法從字串中刪除特殊字元 - 在 Python 中使用正規表示式從字串中刪除特殊字元
在本文中,我們將討論在 Python 中刪除字串中所有特殊字元的各種方法。我們可以通過使用函式或正規表示式從字串中刪除特殊字元。
在 Python 中使用 str.isalnum() 方法從字串中刪除特殊字元
str.isalnum() 方法如果字元是字母數字字元,即字串中沒有特殊字元,則返回 True。如果字串中有任何特殊字元,它將返回 False。
為了從字串中刪除特殊字元,我們必須檢查字元是否是字母數字字元,否則將其刪除。這個方法的實現例子如下。
string = "Hey! What's up bro?"
new_string = "".join(char for char in string if char.isalnum())
print(new_string)
輸出:
HeyWhatsupbro
在 Python 中使用 filter(str.isalnum, string) 方法從字串中刪除特殊字元
為了從字串中刪除特殊字元,我們也可以使用 filter(str.isalnum, string) 方法,與上面解釋的方法類似。但在這種方法中,我們將不使用 str.isalnum() 方法的 for 迴圈和 if 語句,而是使用 filter() 函式。
示例程式碼:
string = "Hey! What's up bro?"
new_string = "".join(filter(str.isalnum, string))
print(new_string)
HeyWhatsupbro
在 Python 中使用正規表示式從字串中刪除特殊字元
為了從字串中刪除特殊字元,我們可以寫一個正規表示式來自動刪除字串中的特殊字元。這個正規表示式將是 [^a-zA-Z0-9],其中^代表除了括號中的字元之外的任何字元,a-zA-Z0-9 代表字串只能有小寫字母以及數字。
示例程式碼:
import re
string = "Hey! What's up bro?"
new_string = re.sub(r"[^a-zA-Z0-9]", "", string)
print(new_string)
輸出:
HeyWhatsupbro
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe