0

我有一些字符串 X,我希望一次性删除分号、句点、逗号、冒号等。有没有一种不需要大量 .replace(somechar,"") 调用链的方法?

4

4 回答 4

1

您可以使用re.sub模式匹配和替换。以下内容仅替换hi空字符串:

In [1]: s = 'byehibyehbyei'

In [1]: re.sub('[hi]', '', s)
Out[1]: 'byebyebye'

别忘了import re

于 2013-05-13T01:29:42.727 回答
1
>>> import re
>>> foo = "asdf;:,*_-"
>>> re.sub('[;:,*_-]', '', foo)
'asdf'
  • [;:,*_-]- 要匹配的字符列表
  • ''- 将匹配替换为空
  • 使用字符串foo.

有关更多信息,请查看re.sub(pattern, repl, string, count=0, flags=0)文档

于 2013-05-13T01:30:11.083 回答
1

您可以将该translate方法与第一个参数一起使用None

string2 = string1.translate(None, ";.,:")

或者,您可以使用以下filter功能

string2 = filter(lambda x: x not in ";,.:", string1)

请注意,这两个选项仅适用于非 Unicode 字符串且仅适用于 Python 2。

于 2013-05-13T01:30:48.950 回答
0

不知道速度,但这是另一个不使用re.

commas_and_stuff = ",+;:"
words = "words; and stuff!!!!"
cleaned_words = "".join(c for c in words if c not in commas_and_stuff)

给你:

“文字和东西!!!!”

于 2013-05-13T01:48:15.677 回答