Python正则表达式可过滤与模式匹配的字符串列表 [英] Python regular expression to filter list of strings matching a pattern

查看:376
本文介绍了Python正则表达式可过滤与模式匹配的字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用R的次数更多,而在R中使用起来更容易:

I use R a lot more and it is easier for me to do it in R:

> test <- c('bbb', 'ccc', 'axx', 'xzz', 'xaa')
> test[grepl("^x",test)]
[1] "xzz" "xaa"

但是如果test是列表,如何在python中执行呢?

But how to do it in python if test is a list?

P.S.我正在使用Google的python练习来学习python.而且我更喜欢使用回归表达式.

P.S. I am learning python using google's python exercise. And I prefer using regression expression.

推荐答案

您可以使用以下内容查找列表中的任何字符串是否以'x'

You can use the following to find if any of the strings in list starts with 'x'

>>> [e for e in test if e.startswith('x')]
['xzz', 'xaa']
>>> any(e.startswith('x') for e in test)
True

这篇关于Python正则表达式可过滤与模式匹配的字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆