我有一套措辞如下:
['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我得到的结果是:
嘿,你好吗? 我叫马修斯。 我讨厌蔬菜 炸薯条泡了出来
预期结果是:
你? 马修斯。 湿透
发布于 2013-08-01 04:46:05
使用endswith()方法。
>>> for line in testList:
for word in line.split():
if word.endswith(('?', '.', 'gy')) :
print word输出:
you?
Mathews.
soggy发布于 2013-08-01 04:48:41
在元组中使用端部。
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发布于 2013-08-01 05:06:57
你们关系很好。
只需转义模式中的特殊字符(?和.):
re.search(r'(\?|\.|gy)$', w)文档中的更多细节。
https://stackoverflow.com/questions/17985407
复制相似问题