Reputation: 3131
I have characters in the middle of a string that I want to get rid of. These characters are =
, p
,, and
H
. Since they are not the leftmost and the rightmost characters in the string, I cannot use strip()
. Is there a function that gets rid of a certain character in any location in a string?
Upvotes: 1
Views: 142
Reputation: 774
My usual tool for this is the regular expression.
>>> import re
>>> invalidCharacters = r'[=p H]'
>>> mystring = re.sub(invalidCharacters, '', ' poH==hHoPPp p')
'ohoPP'
If you need to constrain the number (i.e., the count) of characters you remove, see the count
argument.
Upvotes: 1
Reputation: 362537
The usual tool for this job is str.translate
https://docs.python.org/2/library/stdtypes.html#str.translate
>>> 'hello=potato'.translate(None, '=p')
'hellootato'
Upvotes: 8
Reputation: 34657
Check the .replace() function:
> 'aaba'.replace('a','').replace('b','')
< ''
Upvotes: 2