如何在 Python 中去除字串中的所有特殊字元、標點符號和空格?


在本文中,我們將瞭解如何在 Python 中去除字串中的所有特殊字元、標點符號和空格。

第一種方法是透過使用 isalnum() 方法迭代字串的每個字元,並使用 for 迴圈。我們將使用 isalnum() 檢查每個字元是否為字母或數字,如果不是,則將其移除,否則繼續檢查下一個字元。

如果字串中的每個字元都是字母數字字元,則 isalnum() 方法返回 True(字母或數字)。如果不是,則返回 False。

示例

在下面給出的示例中,我們以字串作為輸入,並使用 isalnum() 和 for 迴圈去除空格和特殊字元,並列印結果字串 

str1 = "Welcome #@ !! to Tutorialspoint123"

print("The given string is")
print(str1)

print("Removing special characters and white spaces")
print(''.join(i for i in str1 if i.isalnum()))

輸出

以上示例的輸出如下所示:−

The given string is
Welcome #@ !! to Tutorialspoint123
Removing special characters and white spaces
WelcometoTutorialspoint123

使用 filter() 和 isalnum() 方法

第二種方法是使用 filter() isalnum()。這種方法與第一種方法類似,但我們使用 filter() 代替 for 迴圈和 if 語句,並使用 isalnum() 檢查給定字元是否為字母或數字。

示例

在下面給出的示例中,我們以字串作為輸入,並使用 filter() 和 isalnum() 去除所有空格和特殊字元,並列印結果字串 

str1 = "Welcome #@ !! to Tutorialspoint123"

print("The given string is")
print(str1)

print("Removing special characters and white spaces")
print(''.join(filter(str.isalnum, str1)))

輸出

以上示例的輸出如下所示:−

The given string is
Welcome #@ !! to Tutorialspoint123
Removing special characters and white spaces
WelcometoTutorialspoint123

使用正則表示式

第二種技術使用正則表示式。匯入 re 庫,如果尚未安裝,則安裝它以使用它。匯入 re 庫後,我們可以使用正則表示式“[A-Za-z0-9]+”。使用 re.sub 技術,特殊字元和空格將被替換為空格。

示例 

在下面給出的示例中,我們以字串作為輸入,並使用正則表示式去除所有特殊字元和空格,並列印結果字串 

import re
str1 = "Welcome #@ !! to Tutorialspoint123"

print("The given string is")
print(str1)

print("Removing special characters and white spaces")
print(re.sub('[^A-Za-z0-9]+', '', str1))

輸出

以上示例的輸出如下所示:−

The given string is
Welcome #@ !! to Tutorialspoint123
Removing special characters and white spaces
WelcometoTutorialspoint123

更新於: 2022-12-07

6K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告