Search code examples
pythonstringstrip

Remove extra characters in the string in Python


I have couple of strings (each string is a set of words) which has special characters in them. I know using strip() function, we can remove all occurrences of only one specific character from any string. Now, I would like to remove set of special characters (include !@#%&*()[]{}/?<> ) etc.

What is the best way you can get these unwanted characters removed from the strings.

in-str = "@John, It's a fantastic #week-end%, How about () you"

out-str = "John, It's a fantastic week-end, How about you"


Solution

  • import string
    
    s = "@John, It's a fantastic #week-end%, How about () you"
    for c in "!@#%&*()[]{}/?<>":
        s = string.replace(s, c, "")
    
    print s
    

    prints "John, It's a fantastic week-end, How about you"