2010-04-07 90 views

回答

10

使用正則表達式。

import re 
blah = "word word: monty py: thon" 
answer = re.sub(r'\w+:\s?','',blah) 
print answer 

這也將拉出冒號後的單個可選空間。

+0

謝謝! Python的正則表達式文檔相當嚇人:( – veb 2010-04-07 00:21:47

+0

@veb python正則表達式的簡單介紹:http://www.amk.ca/python/howto/regex/ – Jacinda 2010-04-07 00:23:46

+0

@veb:歡迎來到SO。如果發佈的答案是你在找什麼,按複選標記圖標以「接受」它 – 2010-04-07 00:25:02

0

這消除其與結尾的所有詞語 「:」:

def RemoveDynamicWords(s): 
    L = [] 
    for word in s.split(): 
     if not word.endswith(':'): 
      L.append(word) 
    return ' '.join(L) 
print RemoveDynamicWords('word: blah') 

或用生成器表達式:

print ' '.join(i for i in word.split(' ') if not i.endswith(':')) 
+0

@David:這不是一個生成器表達式,這是一個列表表達式 – 2010-04-07 01:04:24

+0

感謝您的更正! – cryo 2010-04-07 03:05:09

0
[ chunk for chunk in line.split() if not chunk.endswith(":") ] 

這將創建的列表。你可以在之後加入他們。

相關問題