如何在 Python 中从字符串中删除标点符号

字符串是不同字符、字母、数字、特殊字符和标点符号的组合。 有时我们需要去除标点符号来处理字符串,所以在本文中,我们将讨论使我们能够从字符串中去除标点符号的方法。

1. 通过使用 translate() 方法

2. 通过使用 re.sub() 方法

3. 使用for循环和replace函数

1. 通过使用 translate() 方法

这是从字符串中删除标点符号的最快方法之一。 translate() 方法将翻译表作为参数,该参数由 maketrans() 方法创建并从字符串中删除标点符号。

例子:

pun = '''!()-[]{};:'",<>./[email protected]#$%^&*_~'''  A = 'wow! what? is this []punctuation.'  B = A.translate(str.maketrans('', '', pun))  print(B)

图 1:使用 translate() 方法

输出: