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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16050952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:40:41  来源:igfitidea点击:

How to remove all the punctuation in a string? (Python)

python

提问by Wuchun Aaron

For example:

例如:

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

Can I just do this?

我可以这样做吗?

asking.strip("!'?")

采纳答案by ?yvind Robertsen

A really simple implementation is:

一个非常简单的实现是:

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

and keep adding any other types of punctuation.

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

A more efficient way would be

更有效的方法是

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

Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python

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

回答by thkang

import string

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

filter with string.punctuation.

过滤器string.punctuation

回答by marcin_koss

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

回答by Brenden Brown

Strip won't work. It only removes leading and trailing instances, not everything in between: http://docs.python.org/2/library/stdtypes.html#str.strip

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

Having fun with filter:

享受过滤器的乐趣:

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