2013-03-08 166 views
0

我有一个这样的字符串:如何使用python从文本中删除特定的符号?

字符串=“这是我2013年2月11日的文字,&它包含了这样的人物! (例外)'

这些是我想要从我的字符串中删除的符号。

!, @, #, %, ^, &, *, (,), _, +, =, `,/

我曾尝试是:

listofsymbols = ['!', '@', '#', '%', '^', '&', '*', '(', ')', '_', '+', '=', '`', '/'] 
exceptionals = set(chr(e) for e in listofsymbols) 
string.translate(None,exceptionals) 

的错误是:

的整数需要

请帮我做这个!

+1

http://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string- in-python 这可能是有用的! – 2013-03-08 06:32:14

+0

@达达,感谢编辑:) – MHS 2013-03-08 07:30:24

回答

7

试试这个

>>> my_str = 'This is my text of 2013-02-11, & it contained characters like this! (Exceptional)' 
>>> my_str.translate(None, '[email protected]#%^&*()_+=`/') 
This is my text of 2013-02-11, it contained characters like this Exceptional 

另外,请从命名中已内置名称或标准库的一部分变量避免。

3

这个怎么样?我还将string更名为s,以避免它与内置模块string混淆。

>>> s = 'This is my text of 2013-02-11, & it contained characters like this! (Exceptional)' 
>>> listofsymbols = ['!', '@', '#', '%', '^', '&', '*', '(', ')', '_', '+', '=', '`', '/'] 
>>> print ''.join([i for i in s if i not in listofsymbols]) 
This is my text of 2013-02-11, it contained characters like this Exceptional 
+0

我会建议类似的东西;两个小点:名称“listofsymbols”可以被锐化为“filtersymbols”,并且列表符号有点笨拙,因为一个简单的字符串也可以工作。 – guidot 2013-03-08 08:10:44

+0

@guidot。一,名称无关紧要(除了与内置函数混淆外)。而字符串是不可变的,那么你会如何做你的第二个建议? – TerryA 2013-03-08 08:17:16

+0

filtersymbols IS不可变(字符串表示法也可以防止像'@'而不是'@'这样的错误),因为它只用于查找;尽管名称对于他们为人类编写的编译器无关紧要。 – guidot 2013-03-08 08:36:54

0

另一个建议,容易扩展到更复杂的过滤器标准或其它输入数据类型:

from itertools import ifilter 

def isValid(c): return c not in "[email protected]#%^&*()_+=`/" 

print "".join(ifilter(isValid, my_string)) 
相关问题