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
How to Remove only Trailing Whitespace and Characters from Strings in Python. To remove only trailing whitespace and characters, use the . rstrip() method.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With