views:

95

answers:

3

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
FWIW this requires Python 3.x.
Marius Gedminas
@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
+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
you don't need list comprehension there
SilentGhost
Indeed, it's been a long day.
DisplacedAussie
I'd use 'if x not in set(remove_these)`.
Robert Rossney
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
@Marius: don't suspect, do benchmarks
John Machin
Actually I did some benchmarks with timeit, then got embarrassed about premature microoptimization and didn't post them.
Marius Gedminas
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
Regex isn't ideal for character replacement. The regex has to be compiled and executed which makes it slow.
Thomas O
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
There are many other problems with this suggestion, however, as you'll discover if you set `charsToRemove` to `^x` or `0-9`.
Robert Rossney
@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