写入If条件以过滤掉第一个单词

时间:2013-08-13 09:11:25

标签: python string search

我有一个字符串:

  父亲吃了一根香蕉,睡在羽毛上

我的部分代码如下所示:

...

if word.endswith(('ther')):
   print word

这会打印feather以及Father

但我想修改此if condition,因此它不会将此搜索应用于句子的第一个单词。因此结果应该只打印feather

我尝试过and,但它不起作用:

...

if word.endswith(('ther')) and word[0].endswith(('ther')):
   print word

这不起作用。帮助

4 个答案:

答案 0 :(得分:6)

您可以使用范围跳过第一个单词并将endswith()函数应用于其余单词,例如:

s = 'Father ate a banana and slept on a feather'
[w for w in s.split()[1:] if w.endswith('ther')]

答案 1 :(得分:2)

你可以构建一个正则表达式:

import re
re.findall(r'(\w*ther)',s)[1:]
['feather']

答案 2 :(得分:2)

如果我理解你的问题,如果它是字符串中的第一个单词,你不希望它打印出来。所以,你可以复制字符串并删除第一个单词。

我会引导你完成它。假设你有这个字符串:

s = "Father ate a banana and slept on a feather"

您可以通过运行s.split()并捕获该输出来拆分它:

['Father', 'ate', 'a', 'banana', 'and', 'slept', 'on', 'a', 'feather']

因此,如果你想要除第一个之外的所有单词,你可以使用索引[1:]。您可以通过加入空格来组合单词列表​​。

s1 = "Father ate a banana and slept on a feather" s2 = " ".join(s1.split()[1:])

字符串s2现在将如下:

ate a banana and slept on a feather

您可以使用该字符串并迭代上面的单词。

答案 3 :(得分:1)

如果你想避免制作一个临时字符串

[w for i, w in enumerate(s.split()) if w.endswith('ther') and i]