简体   繁体   English

检查字符串的开头是否与字符串列表中的某些内容匹配(python)

[英]Check if the beginning of a string matches something from a list of strings (python)

I have got a list of strings that I am calling a filter. 我有一个称为过滤器的字符串列表。

filter = ["/This/is/an/example", "/Another/example"]

Now I want to grab only the strings from another list that start with one of these two (or more, the list will be dynamic). 现在,我只想从另一个以这两个中的一个开头的列表中获取字符串(或更多,列表将是动态的)。 So suppose my list of strings to check is this. 因此,假设我要检查的字符串列表是这个。

to_check= ["/This/is/an/example/of/what/I/mean", "/Another/example/this/is/", "/This/example", "/Another/freaking/example"]

When I run it through the filter, I would get a returned list of 当我通过过滤器运行它时,我会得到一个返回的列表

["/This/is/an/example/of/what/I/mean", "/Another/example/this/is"]

Does anyone know if python has a way to do what I am talking about? 有谁知道python是否有办法做我在说的事情? Grabbing only the strings from a list that start with something from another list? 仅抓取列表中以其他列表中的某一个开头的字符串?

Make filter a tuple and use str.startswith() , it takes either one string or a tuple of strings to test for: 使filter一个元组,并使用str.startswith() ,它需要一个字符串或一个字符串元组来测试:

filter = tuple(filter)

[s for s in to_check if s.startswith(filter)]

Demo: 演示:

>>> filter = ("/This/is/an/example", "/Another/example")
>>> to_check = ["/This/is/an/example/of/what/I/mean", "/Another/example/this/is/", "/This/example", "/Another/freaking/example"]
>>> [s for s in to_check if s.startswith(filter)]
['/This/is/an/example/of/what/I/mean', '/Another/example/this/is/']

Be careful, when prefix-matching with paths, you generally want to append trailing path separators so that /foo/bar doesn't match /foo/bar_and_more/ paths. 注意,在与路径进行前缀匹配时,通常需要附加尾随路径分隔符,以使/foo/bar/foo/bar_and_more/路径不匹配。

Using regular expression. 使用正则表达式。

Try below 试试下面

import re
filter = ["/This/is/an/example", "/Another/example"]
to_check= ["/This/is/an/example/of/what/I/mean", "/Another/example/this/is/", "/This/example", "/Another/freaking/example"]

for item in filter:
    for item1 in to_check:
        if re.match("^"+item,item1):
             print item1
             break

Output 输出量

/This/is/an/example/of/what/I/mean
/Another/example/this/is/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM