从Python字符串中删除多种类型的字符

时间:2013-05-13 01:26:03

标签: python regex string

我有一些字符串X,我希望一次性删除分号,句号,逗号,冒号等。有没有办法做到这一点,不需要一大串.replace(somechar,“”)调用?

4 个答案:

答案 0 :(得分:1)

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

In [1]: s = 'byehibyehbyei'

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

别忘了import re

答案 1 :(得分:1)

>>> import re
>>> foo = "asdf;:,*_-"
>>> re.sub('[;:,*_-]', '', foo)
'asdf'
  • [;:,*_-] - 要匹配的字符列表
  • '' - 替换为无匹配
  • 使用字符串foo

有关详细信息,请查看re.sub(pattern, repl, string, count=0, flags=0) documentation

答案 2 :(得分:1)

您可以使用translate方法使用第一个参数None

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

或者,您可以使用filter function

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

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

答案 3 :(得分:0)

不知道速度,但这是另一个不使用re的例子。

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

给你:

  

'单词和东西!!!!'