4

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 4

9
>>> s = 'stringToModify' >>> rem = 'oi' >>> s.translate(str.maketrans(dict.fromkeys(rem))) 'strngTMdfy' 
Sign up to request clarification or add additional context in comments.

3 Comments

FWIW this requires Python 3.x.
@Marius: implementing it in py2k is even simpler. as docs show the solution for precisely this problem
@SilentGhost maketrans(dict.fromkeys(rem) will generate error maketrans() accepts two arguments
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' 

5 Comments

you don't need list comprehension there
Indeed, it's been a long day.
I'd use 'if x not in set(remove_these)`.
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.
Actually I did some benchmarks with timeit, then got embarrassed about premature microoptimization and didn't post them.
2

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

-1

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

Regex isn't ideal for character replacement. The regex has to be compiled and executed which makes it slow.
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.
There are many other problems with this suggestion, however, as you'll discover if you set charsToRemove to ^x or 0-9.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.