how do i write a function removeThese(stringToModify,charsToRemove) that will return a string which is the original stringToModify string with the characters in charsToRemove removed from it.
+6
A:
>>> s = 'stringToModify'
>>> rem = 'oi'
>>> s.translate(str.maketrans(dict.fromkeys(rem)))
'strngTMdfy'
SilentGhost
2010-10-06 16:28:35
FWIW this requires Python 3.x.
Marius Gedminas
2010-10-06 22:51:29
@Marius: implementing it in py2k is even simpler. as [docs show the solution for precisely this problem](http://docs.python.org/library/stdtypes.html#str.translate)
SilentGhost
2010-10-06 22:56:36
+3
A:
>>> 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'
DisplacedAussie
2010-10-06 16:31:20
That would probably re-create the set() every time in the loop. I'd suggest remove_these = set('aeiou'), only I suspect for 5 characters linear searching may be faster than hashing.
Marius Gedminas
2010-10-06 22:49:49
Actually I did some benchmarks with timeit, then got embarrassed about premature microoptimization and didn't post them.
Marius Gedminas
2010-10-12 12:03:34
A:
Use regular expressions:
import re
newString = re.sub("[" + charsToRemove + "]", "", stringToModify)
As a concrete example, the following will remove all occurrences of "a", "m", and "z" from the sentence:
import re
print re.sub("[amz]", "", "the quick brown fox jumped over the lazy dog")
This will remove all characters from "m" through "s":
re.sub("[m-s]", "", "the quick brown fox jumped over the lazy dog")
Abhi
2010-10-06 16:32:26
Regex isn't ideal for character replacement. The regex has to be compiled and executed which makes it slow.
Thomas O
2010-10-06 16:34:00
True, but regex can be compiled if they are going to be re-used multiple times, and they support much more complex replacement operations. In my experience, such convenience often trumps speed considerations in most programming tasks.
Abhi
2010-10-06 16:41:42
There are many other problems with this suggestion, however, as you'll discover if you set `charsToRemove` to `^x` or `0-9`.
Robert Rossney
2010-10-06 19:56:25
@Robert Rossney. `re.escape(charsToRemove)` would overcome that problem, in case anyone reads this and wonders. But regexes are still not the best solution to this problem. `str.translate` for the win.
Day
2010-10-06 23:12:57