我有一些字符串,我想从其中删除一些不需要的字符。例如:Adam'sApple ----> AdamsApple
。(不区分大小写)有人能帮我吗,我需要最快的方法来做,因为我有几百万条记录需要打磨。谢谢
发布于 2010-05-06 20:09:30
一种简单的方法:
>>> s = "Adam'sApple"
>>> x = s.replace("'", "")
>>> print x
'AdamsApple'
..。或者看看regex substitutions。
发布于 2014-09-19 06:41:16
这是一个删除所有恼人的ascii字符的函数,唯一的例外是"&“,它被替换为"and”。我使用它来管理文件系统,并确保所有文件都遵循我坚持每个人都使用的文件命名方案。
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
发布于 2010-05-06 22:20:57
删除translate方法的第二个参数中的所有字符:
>>> "Adam's Apple!".translate(None,"'!")
'Adams Apple'
注意: translate要求Python 2.6或更高版本使用None作为第一个参数,否则必须是长度为256的转换字符串。对于2.6之前的版本,可以使用string.maketrans('','')代替None。
https://stackoverflow.com/questions/2780904
复制相似问题