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


在這篇文章中,我們將瞭解如何在 Python 中從字串中刪除所有特殊字元、標點符號和空格。

第一種方法是使用 **isalnum()** 方法遍歷字串中的每個字元。我們將使用 **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+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.