2013-05-13 100 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])