如何在Python中删除字符串中的所有标点符号?

9

例如:

asking="hello! what's your name?"

我可以直接这样做吗?

asking.strip("!'?")

2
你看过这个网站吗?https://dev59.com/12865IYBdhLWcg3wLrlE - Garrett Hyde
4个回答

22

一个非常简单的实现方式是:

out = "".join(c for c in asking if c not in ('!','.',':'))

并继续添加任何其他类型的标点符号。

一种更有效的方法是

import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)

编辑:这里有更多关于效率和其他实现的讨论: 在Python中从字符串中删除标点符号的最佳方法


1
strip() 不起作用。请参见 http://docs.python.org/2/library/stdtypes.html#str.strip - Brenden Brown
@BrendenBrown 您说得没错。半年不看 Python,结果怎么样呢?接下来就是可耻的编辑了。 - Øyvind Robertsen
删除时,您可以将最后一行简化为 out = stringIn.translate(None, string.punctuation)(请参见 https://docs.python.org/2/library/stdtypes.html#str.translate) - asmaier
对于Python 3,https://dev59.com/yFsX5IYBdhLWcg3wDb2L#34294398 - xtian

15
import string

asking = "".join(l for l in asking if l not in string.punctuation)

使用string.punctuation进行过滤。


0

这个方法可行,但可能有更好的解决方案。

asking="hello! what's your name?"
asking = ''.join([c for c in asking if c not in ('!', '?')])
print asking

在这种情况下,您不需要内部列表,这将返回“hellowhat'syourname”。 - Burhan Khalid
@BurhanKhalid,你是对的,内部列表不需要,但输出是正确的。 - marcin_koss

0

Strip不起作用。它只删除前导和尾随实例,而不是中间的所有内容:http://docs.python.org/2/library/stdtypes.html#str.strip

使用过滤器很有趣:

import string
asking = "hello! what's your name?"
predicate = lambda x:x not in string.punctuation
filter(predicate, asking)

如果你使用的是Python 3.x,那么在filter()函数周围加上list()非常重要,因为许多内置函数不再返回lists而是特殊的iterable对象。此外,你似乎忽略了在第二行字符串周围放置input(或者对于Python 2.x是raw_input),并且你应该在最后一行放置类似asking = ...的东西。 - SimonT
1
在3.x中似乎不鼓励使用这种方法:https://dev59.com/DWYr5IYBdhLWcg3wfKP_ - Brenden Brown
当你不得不使用lambda时,filter会变得丑陋而缓慢,不幸的是,你的替代方案是''.join(ifilterfalse(partial(contains, punctuation), asking)) - jamylak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接