Eric B
Eric B

Reputation: 41

python: how to remove certain characters

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.

Upvotes: 4

Views: 5189

Answers (4)

Will
Will

Reputation: 4713

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"
>>>

Upvotes: 2

Abhi
Abhi

Reputation: 1147

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")

Upvotes: -1

DisplacedAussie
DisplacedAussie

Reputation: 4694

>>> 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'

Upvotes: 3

SilentGhost
SilentGhost

Reputation: 319551

>>> s = 'stringToModify'
>>> rem = 'oi'
>>> s.translate(str.maketrans(dict.fromkeys(rem)))
'strngTMdfy'

Upvotes: 9

Related Questions