2013-07-28 29 views
1

我有一個單詞列表如下:識別單詞與特定的字符關閉

apple 
grapes 
pappu 
pop 
seeds 

我需要確定並顯示所有與該角色up結束的話。 預期的輸出如下:這裏不需要

p = [w for w in theWord if re.search('(u|p)$', w)] 
print p 
+0

你的正則表達式應該工作。 「TheWord」實際上是什麼樣子? – Blender

+0

很可能是從文件中讀取並以'\ n'結尾。 –

+0

@limelights正則表達式會自動忽略換行符。 –

回答

4

使用str.endswithregex

pappu 
pop 

我的代碼,這是不正確。

p = [w for w in theWord if w.endswith(('p','u'))] 

演示:

>>> theWord = ['apple', 'grapes', 'pappu', 'pop', 'seeds'] 
>>> p = [w for w in theWord if w.endswith(('p','u'))] 
for w in p: 
    print w 
...  
pappu 
pop 

BTW你的代碼是好的,你只需要一個for循環,讓您的預期輸出:

>>> p = [w for w in theWord if re.search('(u|p)$', w)] 
>>> for w in p: 
...  print w 
...  
pappu 
pop 
1

你可以這樣做:

words = ['apple','grapes','pappu','pop','seeds',''] 

for word in words: 
    if word[-1:] == 'p' or word[-1:]== 'u': 
     print word 

並索引每個單詞的最後一個字母,如果他們的staement匹配,則做任何與他們

+0

如果列表包含空字符串,該怎麼辦? –

+0

固定它,但你的解決方案可能更好,更短 – Serial

+0

@just只是'如果單詞'是足夠的,並且最好使用切片:'單詞[-1:] =='p'' –

0

您可以隨時使用切片,反向索引:

>>> theWord = ['apple', 'grapes', 'pappu', 'pop', 'seeds'] 
>>> [w for w in theWord if w[-1].lower() in ['p', 'u']] 
['pappu', 'pop'] 
>>> 

注: .lower()只需要,如果你想獲得以P和U結尾的單詞

+0

http://stackoverflow.com/questions/17905563/identify-words-closing-with-the-a-particular-character/17905567#comment26155172_17905584 –