例如:
asking="hello! what's your name?"
我可以这样做吗?
asking.strip("!'?")
一个非常简单的实现是:
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
import string
asking = "".join(l for l in asking if l not in string.punctuation)
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
剥离将不起作用。它只删除前导和尾随实例,而不是介于两者之间的所有内容: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)