Removing unwanted characters from a string in Python

前端 未结 9 2039
暖寄归人
暖寄归人 2021-01-18 09:06

I have some strings that I want to delete some unwanted characters from them. For example: Adam\'sApple ----> AdamsApple.(case insensitive) Can someone help

9条回答
  •  别那么骄傲
    2021-01-18 09:51

    Here is a function that removes all the irritating ascii characters, the only exception is "&" which is replaced with "and". I use it to police a filesystem and ensure that all of the files adhere to the file naming scheme I insist everyone uses.

    def cleanString(incomingString):
        newstring = incomingString
        newstring = newstring.replace("!","")
        newstring = newstring.replace("@","")
        newstring = newstring.replace("#","")
        newstring = newstring.replace("$","")
        newstring = newstring.replace("%","")
        newstring = newstring.replace("^","")
        newstring = newstring.replace("&","and")
        newstring = newstring.replace("*","")
        newstring = newstring.replace("(","")
        newstring = newstring.replace(")","")
        newstring = newstring.replace("+","")
        newstring = newstring.replace("=","")
        newstring = newstring.replace("?","")
        newstring = newstring.replace("\'","")
        newstring = newstring.replace("\"","")
        newstring = newstring.replace("{","")
        newstring = newstring.replace("}","")
        newstring = newstring.replace("[","")
        newstring = newstring.replace("]","")
        newstring = newstring.replace("<","")
        newstring = newstring.replace(">","")
        newstring = newstring.replace("~","")
        newstring = newstring.replace("`","")
        newstring = newstring.replace(":","")
        newstring = newstring.replace(";","")
        newstring = newstring.replace("|","")
        newstring = newstring.replace("\\","")
        newstring = newstring.replace("/","")        
        return newstring
    

提交回复
热议问题