首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Python中移除字符串中不需要的字符

在Python中移除字符串中不需要的字符
EN

Stack Overflow用户
提问于 2010-05-06 20:05:14
回答 8查看 20.2K关注 0票数 6

我有一些字符串,我想从其中删除一些不需要的字符。例如:Adam'sApple ----> AdamsApple。(不区分大小写)有人能帮我吗,我需要最快的方法来做,因为我有几百万条记录需要打磨。谢谢

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2010-05-06 20:09:30

一种简单的方法:

代码语言:javascript
复制
>>> s = "Adam'sApple"
>>> x = s.replace("'", "")
>>> print x
'AdamsApple'

..。或者看看regex substitutions

票数 6
EN

Stack Overflow用户

发布于 2014-09-19 06:41:16

这是一个删除所有恼人的ascii字符的函数,唯一的例外是"&“,它被替换为"and”。我使用它来管理文件系统,并确保所有文件都遵循我坚持每个人都使用的文件命名方案。

代码语言:javascript
复制
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
票数 6
EN

Stack Overflow用户

发布于 2010-05-06 22:20:57

删除translate方法的第二个参数中的所有字符:

代码语言:javascript
复制
>>> "Adam's Apple!".translate(None,"'!")
'Adams Apple'

注意: translate要求Python 2.6或更高版本使用None作为第一个参数,否则必须是长度为256的转换字符串。对于2.6之前的版本,可以使用string.maketrans('','')代替None。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2780904

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档