Python:如何删除特定字符

4

如何编写一个函数removeThese(stringToModify,charsToRemove),它将返回一个新的字符串,该字符串是从原始字符串stringToModify中删除了charsToRemove中出现的字符。

4个回答

9
>>> s = 'stringToModify'
>>> rem = 'oi'
>>> s.translate(str.maketrans(dict.fromkeys(rem)))
'strngTMdfy'

2
这需要使用Python 3.x。 - Marius Gedminas
4
在Python2中实现它甚至更简单,因为文档展示了解决此问题的方案 - SilentGhost
@SilentGhost,maketrans(dict.fromkeys(rem)) 会生成错误,因为 maketrans() 函数需要接受两个参数。 - Grijesh Chauhan

3
>>> string_to_modify = 'this is a string'
>>> remove_these = 'aeiou'
>>> ''.join(x for x in string_to_modify if x not in remove_these)
'ths s  strng'

2
你不需要使用列表推导式。 - SilentGhost
1
确实,今天过得很漫长。 - DisplacedAussie
我会使用 if x not in set(remove_these) - Robert Rossney
这样做可能会在每次循环中重新创建set()。我建议使用remove_these = set('aeiou'),但是考虑到只有5个字符,线性搜索可能比哈希更快。 - Marius Gedminas
1
其实我用timeit做了一些基准测试,但是因为过早的微优化而感到尴尬,所以没有发布它们。 - Marius Gedminas

2
这是使用lambda函数和Python的filter()方法的机会。 filter接受一个谓词和一个序列,并返回一个仅包含原始序列中谓词为真的项的序列。在这里,我们只想要来自s而不是rm的所有字符。
>>> s = "some quick string 2 remove chars from"
>>> rm = "2q"
>>> filter(lambda x: not (x in rm), s)
"some uick string remove chars from"
>>>

-1
使用正则表达式:
import re
newString = re.sub("[" + charsToRemove + "]", "", stringToModify)

作为一个具体的例子,以下代码将从句子中删除所有出现的 "a"、"m" 和 "z":
import re
print re.sub("[amz]", "", "the quick brown fox jumped over the lazy dog")

这将删除从 "m" 到 "s" 的所有字符:
re.sub("[m-s]", "", "the quick brown fox jumped over the lazy dog")

正则表达式不适合用于字符替换。正则表达式需要编译和执行,这使得它变得很慢。 - Thomas O
真的,但是如果正则表达式将被多次重复使用,它们可以被编译,并且支持更复杂的替换操作。在我的经验中,这种便利通常在大多数编程任务中胜过速度考虑。 - Abhi
3
然而,如果你将 charsToRemove 设为 ^x0-9,你会发现这个建议还有许多其他问题。 - Robert Rossney
1
@Robert Rossney。如果有人阅读此内容并想知道,re.escape(charsToRemove)可以解决这个问题。但是正则表达式仍然不是解决此问题的最佳方案。str.translate才是胜利者。 - Day

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接