Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I strip a string given a list of unwanted characters? Python

Is there a way to pass in a list instead of a char to str.strip() in python? I have been doing it this way:

unwanted = [c for c in '!@#$%^&*(FGHJKmn']
s = 'FFFFoFob*&%ar**^'
for u in unwanted:
  s = s.strip(u)
print s

Desired output, this output is correct but there should be some sort of a more elegant way than how i'm coding it above:

oFob*&%ar
like image 429
alvas Avatar asked Nov 01 '25 10:11

alvas


2 Answers

Strip and friends take a string representing a set of characters, so you can skip the loop:

>>> s = 'FFFFoFob*&%ar**^'
>>> s.strip('!@#$%^&*(FGHJKmn')
'oFob*&%ar'

(the downside of this is that things like fn.rstrip(".png") seems to work for many filenames, but doesn't really work)

like image 155
Fredrik Avatar answered Nov 04 '25 01:11

Fredrik


Since, you are looking to not delete elements from the middle, you can just use.

>>> 'FFFFoFob*&%ar**^'.strip('!@#$%^&*(FGHJKmn')
'oFob*&%ar'

Otherwise, Use str.translate().

>>> 'FFFFoFob*&%ar**^'.translate(None, '!@#$%^&*(FGHJKmn')
'oobar'
like image 25
Sukrit Kalra Avatar answered Nov 03 '25 23:11

Sukrit Kalra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!