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

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

最快的从字符串中剥离所有标点符号的方法是使用 str.translate()。您可以使用如下方式−

阅读更多:Python 教程

示例

import string
s = "string. With. Punctuation?"
print s.translate(None, string.punctuation)

输出

这将给我们输出−

string With Punctuation

示例

如果您想要一个更易读的解决方案,可以显式迭代集合并在循环中忽略所有标点符号,如下所示−

s = "string. With. Punctuation?"
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)
print s

输出

这将给我们输出−

string With Punctuation

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程