2009-05-18 249 views
45

我是Python和RegEx的初學者,我想知道如何製作一個字符串,它需要符號並用空格替換它們。任何幫助都很棒。如何使用Python從字符串中刪除符號?

例如:

how much for the maple syrup? $20.99? That's ricidulous!!! 

成:

how much for the maple syrup 20 99 That s ridiculous 
+7

奇怪這個被標記爲要求在一年後一個問題的副本。 – monkut 2014-01-30 00:52:00

+0

我的建議是閱讀[re](http://docs.python.org/library/re.html)庫的文檔。它包括一些很好的例子。 – 2009-05-18 02:00:02

回答

90

一種方法,使用regular expressions

>>> s = "how much for the maple syrup? $20.99? That's ridiculous!!!" 
>>> re.sub(r'[^\w]', ' ', s) 
'how much for the maple syrup 20 99 That s ridiculous ' 
  • \w將匹配的字母數字字符和下劃線

  • ​​將匹配任何的字母或下劃線

+13

應該注意,括號外的^ \ w表示'匹配行首的字母數字字符'。只是在括號內([^ \ w]),插入符號表示'忽略此處的每個字符' – cmptrgeekken 2009-05-18 02:10:29

3

我往往只是打開控制檯並尋找對象的方法解決。很多時候它已經在那裏:

>>> a = "hello ' s" 
>>> dir(a) 
[ (....) 'partition', 'replace' (....)] 
>>> a.replace("'", " ") 
'hello s' 

簡短回答:使用string.replace()

20

有時需要更長的時間來找出正則表達式,而不是隻是把它寫出來的蟒蛇:

import string 
s = "how much for the maple syrup? $20.99? That's ricidulous!!!" 
for char in string.punctuation: 
    s = s.replace(char, ' ') 

如果需要其他字符,你可以改變它使用白名單或擴展您的黑名單。

樣品白名單:使用發電機表達

whitelist = string.letters + string.digits + ' ' 
new_s = '' 
for char in s: 
    if char in whitelist: 
     new_s += char 
    else: 
     new_s += ' ' 

樣品白名單:

whitelist = string.letters + string.digits + ' ' 
new_s = ''.join(c for c in s if c in whitelist) 
相關問題