Python: how to remove specific characters

how to write a removeThese function (stringToModify, charsToRemove) that will return a string that is the original stringToModify string, with characters in charsToRemove removed from it.

+4
source share
4 answers
>>> s = 'stringToModify' >>> rem = 'oi' >>> s.translate(str.maketrans(dict.fromkeys(rem))) 'strngTMdfy' 
+9
source
 >>> 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' 
+3
source

This is the ability to use the lambda function and the python filter () method. filter takes a predicate and a sequence and returns a sequence containing only those elements from the original sequence for which the predicate is true. Here we just need 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" >>> 
+2
source

Use regular expressions:

 import re newString = re.sub("[" + charsToRemove + "]", "", stringToModify) 

As a specific example, the following excludes all occurrences of "a", "m", and "z" from a sentence:

 import re print re.sub("[amz]", "", "the quick brown fox jumped over the lazy dog") 

This will remove all characters from "m" to "s":

 re.sub("[ms]", "", "the quick brown fox jumped over the lazy dog") 
-1
source

All Articles