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

sha*_*Hwk 10 python

我有一组单词如下:

['Hey, how are you?\n','My name is Mathews.\n','I hate vegetables\n','French fries came out soggy\n']
Run Code Online (Sandbox Code Playgroud)

在上面的句子中,我需要识别以?or .或'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
Run Code Online (Sandbox Code Playgroud)

我得到的结果是:

嘿,你怎么样?

我的名字是马修斯.

我讨厌蔬菜

炸薯条湿透了

预期的结果是:

您?

马修斯.

浸水

Suk*_*lra 12

使用endswith()方法.

>>> for line in testList:
        for word in line.split():
            if word.endswith(('?', '.', 'gy')) :
                print word
Run Code Online (Sandbox Code Playgroud)

输出:

you?
Mathews.
soggy
Run Code Online (Sandbox Code Playgroud)

  • 你不需要调用`strip()`,因为`split()`没有分隔符修剪前导空格. (3认同)

fal*_*tru 5

使用带有元组的结尾.

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
Run Code Online (Sandbox Code Playgroud)

正则表达式替代:

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
Run Code Online (Sandbox Code Playgroud)