如何在 Python 中去除字符串中的所有特殊字符、标点符号和空格?


在本文中,我们将了解如何在 Python 中去除字符串中的所有特殊字符、标点符号和空格。

第一种方法是通过使用 isalnum() 方法迭代字符串的每个字符,并使用 for 循环。我们将使用 isalnum() 检查每个字符是否为字母或数字,如果不是,则将其移除,否则继续检查下一个字符。

如果字符串中的每个字符都是字母数字字符,则 isalnum() 方法返回 True(字母或数字)。如果不是,则返回 False。

示例

在下面给出的示例中,我们以字符串作为输入,并使用 isalnum() 和 for 循环去除空格和特殊字符,并打印结果字符串 

Open Compiler
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

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

使用 filter() 和 isalnum() 方法

第二种方法是使用 filter() isalnum()。这种方法与第一种方法类似,但我们使用 filter() 代替 for 循环和 if 语句,并使用 isalnum() 检查给定字符是否为字母或数字。

示例

在下面给出的示例中,我们以字符串作为输入,并使用 filter() 和 isalnum() 去除所有空格和特殊字符,并打印结果字符串 

Open Compiler
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 技术,特殊字符和空格将被替换为空格。

示例 

在下面给出的示例中,我们以字符串作为输入,并使用正则表达式去除所有特殊字符和空格,并打印结果字符串 

Open Compiler
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+ 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告