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.
4 Answers
>>> s = 'stringToModify' >>> rem = 'oi' >>> s.translate(str.maketrans(dict.fromkeys(rem))) 'strngTMdfy' 3 Comments
Marius Gedminas
FWIW this requires Python 3.x.
SilentGhost
@Marius: implementing it in py2k is even simpler. as docs show the solution for precisely this problem
Grijesh Chauhan
@SilentGhost
maketrans(dict.fromkeys(rem) will generate error maketrans() accepts two arguments>>> 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' 5 Comments
SilentGhost
you don't need list comprehension there
DisplacedAussie
Indeed, it's been a long day.
Robert Rossney
I'd use 'if x not in set(remove_these)`.
Marius Gedminas
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
Actually I did some benchmarks with timeit, then got embarrassed about premature microoptimization and didn't post them.
This is a chance to use a lambda function and the python filter() method. filter takes a predicate and a sequence and returns a sequence containing only those items from the original sequence for which the predicate is true. Here we just want all the characters from s not in 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" >>> Comments
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") 4 Comments
Thomas O
Regex isn't ideal for character replacement. The regex has to be compiled and executed which makes it slow.
Abhi
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.
Robert Rossney
There are many other problems with this suggestion, however, as you'll discover if you set
charsToRemove to ^x or 0-9.Day
@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.