Search for a pattern in a list of strings - Python

Posted by Holtz on Stack Overflow See other posts from Stack Overflow or by Holtz
Published on 2013-11-08T13:45:48Z Indexed on 2013/11/08 15:54 UTC
Read the original article Hit count: 270

Filed under:
|
|

I have a list of strings containing filenames such as,

file_names = ['filei.txt','filej.txt','filek.txt','file2i.txt','file2j.txt','file2k.txt','file3i.txt','file3j.txt','file3k.txt']

I then remove the .txt extension using:

extension = os.path.commonprefix([n[::-1] for n in file_names])[::-1]

file_names_strip = [n[:-len(extension)] for n in file_names]

And then return the last character of each string in the list file_names_strip:

h = [n[-1:] for n in file_names_strip]

Which gives h = ['i', 'j', 'k', 'i', 'j', 'k', 'i', 'j', 'k']

How can i test for a pattern of strings in h? So if i,j,k occur sequentially it would return True and False if not. I need to know this because not all file names are formatted like they are in file_names.

So:

test_ijk_pattern(h) = True

no_pattern = ['1','2','3','1','2','3','1','2','3']

test_ijk_pattern(no_pattern) = False

© Stack Overflow or respective owner

Related posts about python

Related posts about string