sodiumnitrate
sodiumnitrate

Reputation: 3131

Getting rid of certain characters in a string in python

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

Answers (3)

bmhkim
bmhkim

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

wim
wim

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

hd1
hd1

Reputation: 34657

Check the .replace() function:

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

Upvotes: 2

Related Questions