Search code examples
pythonstringstrip

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

Solution

  • 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)