2013-05-13 99 views
2

我有几个字符串(每个字符串是一组字),其中有特殊字符。我知道使用strip()函数,我们可以从任何字符串中删除所有出现的只有一个特定字符。现在,我想删除一组特殊字符(包括@ @#*()[] {} /?<>字符串。删除Python中字符串中的多余字符

在-STR = “@约翰,这是一个梦幻般的#周末%,如何()你”

出海峡=“约翰,这是一个梦幻般的周末,你怎么样“

+0

的'()'将是特别困难没有正则表达式来摆脱。 – bozdoz 2013-05-13 14:49:38

+0

请问**你为什么要这样做?特别是,如果你想防止代码注入攻击,你可能更喜欢_escape_特殊字符,而不是删除它们。这将如何去取决于具体的应用。 – Robin 2013-05-13 19:44:14

回答

2
import string 

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

print s 

打印 “约翰,这是一个梦幻般的周末,你怎么样”

1

strip函数只删除前导字符和尾随字符。 你的目的,我会用蟒蛇set来存储你的角色,遍历您输入的字符串,并创建从set不存在字符新的字符串。根据其他计算器article这应该是有效的。最后,只需通过巧妙的" ".join(output_string.split())构造去除双重空间。

char_set = set("[email protected]#%&*()[]{}/?<>") 
input_string = "@John, It's a fantastiC#week-end%, How about() you" 
output_string = "" 

for i in range(0, len(input_string)): 
    if not input_string[i] in char_set: 
     output_string += input_string[i] 

output_string = " ".join(output_string.split()) 
print output_string 
1

试试这个:

import re 

foo = 'a..!b...c???d;;' 
chars = [',', '!', '.', ';', '?'] 

print re.sub('[%s]' % ''.join(chars), '', foo) 

我相信这是你想要的。

+0

顺便说一下,我建议构建不被foreach循环接受的字符数组,或者以类似的方式来确保动态编辑受限制的字符。 – Dropout 2013-05-13 14:43:34

0

尝试

s = "@John, It's a fantastiC#week-end%, How about() you" 
chars = "[email protected]#%&*()[]{}/?<>" 
s_no_chars = "".join([k for k in s if k not in chars]) 
s_no_chars_spaces = " ".join([ d for d in "".join([k for k in s if k not in chars]).split(" ") if d])