以。结尾的python单词中的字符串比较

时间:2013-08-01 04:44:43

标签: python

我有一组单词如下:

['Hey, how are you?\n','My name is Mathews.\n','I hate vegetables\n','French fries came out soggy\n']

在上面的句子中,我需要识别所有以?.或'gy'结尾的句子。并打印出最后的单词。

我的方法如下:

# words will contain the string i have pasted above.
word = [w for w in words if re.search('(?|.|gy)$', w)]
for i in word:
    print i

我得到的结果是:

  嘿,你好吗?

     

我的名字是Mathews。

     

我讨厌蔬菜

     

炸薯条湿透了

预期结果是:

  

你?

     

马修斯。

     

潮湿

3 个答案:

答案 0 :(得分:10)

使用endswith()方法。

>>> for line in testList:
        for word in line.split():
            if word.endswith(('?', '.', 'gy')) :
                print word

输出:

you?
Mathews.
soggy

答案 1 :(得分:5)

endswith与元组一起使用。

lines = ['Hey, how are you?\n','My name is Mathews.\n','I hate vegetables\n','French fries came out soggy\n']
for line in lines:
    for word in line.split():
        if word.endswith(('?', '.', 'gy')):
            print word

正则表达式替代:

import re

lines = ['Hey, how are you?\n','My name is Mathews.\n','I hate vegetables\n','French fries came out soggy\n']
for line in lines:
    for word in re.findall(r'\w+(?:\?|\.|gy\b)', line):
        print word

答案 2 :(得分:3)

你很亲密。

您只需要在模式中转义特殊字符(?.):

re.search(r'(\?|\.|gy)$', w)

More details in the documentation.