2013-03-08 171 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)) 
相關問題