1

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?

3 Answers 3

8

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'
Sign up to request clarification or add additional context in comments.

6 Comments

Is translate better than replace?
Since you need to remove multiple characters, yes.
@wim But would the order have to be =p? I suspect this would not remove p=.
Note that translate works differently in Python 3.
@TigerhawkT3 I use 2.7, which I forgot to mention. But thank you for the note :)
|
2

Check the .replace() function:

> 'aaba'.replace('a','').replace('b','')
< ''

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.