我有一个单词列表如下:识别单词与特定的字符关闭
apple
grapes
pappu
pop
seeds
我需要确定并显示所有与该角色u
和p
结束的话。 预期的输出如下:这里不需要
p = [w for w in theWord if re.search('(u|p)$', w)]
print p
我有一个单词列表如下:识别单词与特定的字符关闭
apple
grapes
pappu
pop
seeds
我需要确定并显示所有与该角色u
和p
结束的话。 预期的输出如下:这里不需要
p = [w for w in theWord if re.search('(u|p)$', w)]
print p
使用str.endswith
,regex
:
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
你可以这样做:
words = ['apple','grapes','pappu','pop','seeds','']
for word in words:
if word[-1:] == 'p' or word[-1:]== 'u':
print word
并索引每个单词的最后一个字母,如果他们的staement匹配,则做任何与他们
如果列表包含空字符串,该怎么办? –
固定它,但你的解决方案可能更好,更短 – Serial
@just只是'如果单词'是足够的,并且最好使用切片:'单词[-1:] =='p'' –
您可以随时使用切片,反向索引:
>>> theWord = ['apple', 'grapes', 'pappu', 'pop', 'seeds']
>>> [w for w in theWord if w[-1].lower() in ['p', 'u']]
['pappu', 'pop']
>>>
注: .lower()
只需要,如果你想获得以P和U结尾的单词
http://stackoverflow.com/questions/17905563/identify-words-closing-with-the-a-particular-character/17905567#comment26155172_17905584 –
你的正则表达式应该工作。 “TheWord”实际上是什么样子? – Blender
很可能是从文件中读取并以'\ n'结尾。 –
@limelights正则表达式会自动忽略换行符。 –