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?
Add a comment
|
3 Answers
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'
6 Comments
Loocid
Is translate better than replace?
wim
Since you need to remove multiple characters, yes.
sodiumnitrate
@wim But would the order have to be
=p? I suspect this would not remove p=.TigerhawkT3
Note that
translate works differently in Python 3.sodiumnitrate
@TigerhawkT3 I use
2.7, which I forgot to mention. But thank you for the note :) |