9

例如:

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

我可以这样做吗?

asking.strip("!'?")
4

4 回答 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)

编辑:这里有更多关于效率和其他实现的讨论: Best way to strip punctuation from a string in Python

于 2013-04-17T03:36:29.100 回答
15
import string

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

过滤string.punctuation

于 2013-04-17T03:31:55.147 回答
0

This works, but there might be better solutions.

asking="hello! what's your name?"
asking = ''.join([c for c in asking if c not in ('!', '?')])
print asking
于 2013-04-17T03:35:59.097 回答
0

剥离将不起作用。它只删除前导和尾随实例,而不是介于两者之间的所有内容: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)
于 2013-04-17T03:43:22.193 回答