Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python strip() multiple characters?

Tags:

python

I want to remove any brackets from a string. Why doesn't this work properly?

>>> name = "Barack (of Washington)" >>> name = name.strip("(){}<>") >>> print name Barack (of Washington 
like image 704
AP257 Avatar asked Oct 10 '10 11:10

AP257


People also ask

How do you strip a character in Python?

How to Remove only Trailing Whitespace and Characters from Strings in Python. To remove only trailing whitespace and characters, use the . rstrip() method.

What does Strip () do in Python?

The Strip() method in Python removes or truncates the given characters from the beginning and the end of the original string. The default behavior of the strip() method is to remove the whitespace from the beginning and at the end of the string.

How do I remove the first 3 characters from a string in Python?

Use Python to Remove the First N Characters from a String Using Regular Expressions. You can use Python's regular expressions to remove the first n characters from a string, using re's . sub() method. This is accomplished by passing in a wildcard character and limiting the substitution to a single substitution.


1 Answers

Because that's not what strip() does. It removes leading and trailing characters that are present in the argument, but not those characters in the middle of the string.

You could do:

name= name.replace('(', '').replace(')', '').replace ... 

or:

name= ''.join(c for c in name if c not in '(){}<>') 

or maybe use a regex:

import re name= re.sub('[(){}<>]', '', name) 
like image 65
bobince Avatar answered Sep 19 '22 23:09

bobince