Python 识别以特定字符结尾的单词
我有一个单词列表如下:Python 识别以特定字符结尾的单词,python,Python,我有一个单词列表如下: apple grapes pappu pop seeds pappu pop 我想识别并显示以字符u和p结尾的所有单词。 预期产出如下: apple grapes pappu pop seeds pappu pop 我的代码不正确: p = [w for w in theWord if re.search('(u|p)$', w)] print p 使用str.endswith,此处不需要regex p = [w for w in theWord if w.en
apple
grapes
pappu
pop
seeds
pappu
pop
我想识别并显示以字符u
和p
结尾的所有单词。
预期产出如下:
apple
grapes
pappu
pop
seeds
pappu
pop
我的代码不正确:
p = [w for w in theWord if re.search('(u|p)$', w)]
print p
使用
str.endswith
,此处不需要regex
p = [w for w in theWord if w.endswith(('p','u'))]
演示:
顺便说一句,您的代码还可以,您只需要一个for循环即可获得预期的输出:
>>> p = [w for w in theWord if re.search('(u|p)$', w)]
>>> for w in p:
... print w
...
pappu
pop
使用
str.endswith
,此处不需要regex
p = [w for w in theWord if w.endswith(('p','u'))]
演示:
顺便说一句,您的代码还可以,您只需要一个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
并为每个单词的最后一个字母编制索引,如果它们与statement匹配,则对它们执行任何操作
words = ['apple','grapes','pappu','pop','seeds','']
for word in words:
if word[-1:] == 'p' or word[-1:]== 'u':
print word
并为每个单词的最后一个字母编制索引,如果它们与statement匹配,则对它们执行任何操作您始终可以使用切片、反向索引:
>>> theWord = ['apple', 'grapes', 'pappu', 'pop', 'seeds']
>>> [w for w in theWord if w[-1].lower() in ['p', 'u']]
['pappu', 'pop']
>>>
注意:
.lower()
仅当您希望获取以p和U结尾的单词时才需要.lower()您可以始终使用切片、反向索引:
>>> theWord = ['apple', 'grapes', 'pappu', 'pop', 'seeds']
>>> [w for w in theWord if w[-1].lower() in ['p', 'u']]
['pappu', 'pop']
>>>
注意:.lower()
仅当您希望获得以p和U结尾的单词时才需要您的正则表达式应该可以工作。这个词实际上是什么样子的?很可能是从文件中读取的,以\n
@limelights regex自动忽略换行符结尾。@AshwiniChaudhary我不知道,谢谢!)你的正则表达式应该有用。这个词实际上是什么样子的?很可能是从文件中读取的,以\n
@limelights regex自动忽略换行符结尾。@AshwiniChaudhary我不知道,谢谢!)如果列表中包含一个空字符串怎么办?修复了它,但您的解决方案可能更好,而且shorter@just只要如果word
足够,最好使用切片:word[-1:][='p'
不需要如果word!='':代码>现在,切片不会引发索引器
。感谢您纠正我所有的错误,Ashwini,我还在学习:)如果列表包含空字符串怎么办?修复了它,但您的解决方案可能更好,而且shorter@just只要如果word
足够,最好使用切片:word[-1:]=='p'
不需要如果单词!='':代码>现在,切片不会引发索引器
。谢谢你纠正了我所有的错误Ashwini,我还在学习:)