例如:
asking="hello! what's your name?"
我可以直接这样做吗?
asking.strip("!'?")
例如:
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)
编辑:这里有更多关于效率和其他实现的讨论: 在Python中从字符串中删除标点符号的最佳方法
strip()
不起作用。请参见 http://docs.python.org/2/library/stdtypes.html#str.strip - Brenden Brownout = stringIn.translate(None, string.punctuation)
(请参见 https://docs.python.org/2/library/stdtypes.html#str.translate) - asmaierimport string
asking = "".join(l for l in asking if l not in string.punctuation)
使用string.punctuation
进行过滤。
这个方法可行,但可能有更好的解决方案。
asking="hello! what's your name?"
asking = ''.join([c for c in asking if c not in ('!', '?')])
print asking
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)
filter()
函数周围加上list()
非常重要,因为许多内置函数不再返回lists
而是特殊的iterable
对象。此外,你似乎忽略了在第二行字符串周围放置input
(或者对于Python 2.x是raw_input
),并且你应该在最后一行放置类似asking = ...
的东西。 - SimonTlambda
时,filter
会变得丑陋而缓慢,不幸的是,你的替代方案是''.join(ifilterfalse(partial(contains, punctuation), asking))
。 - jamylak