Kate N Kate N - 1 year ago 47
Python Question

Find index position of characters in string

I am trawling through a storage area and the paths look a lot like this:

I wont always know what year is it. I need to find the starting index position of the year

Therefor I am looking for where I find the following in the file name (2010, 2011, 2012, 2013, 2014 etc...)

I have set up a list as follows:

list_ = ['2010', '2011','2012','2013','2014', '2015', '2016']

and I can find if it is in the file name

if any(word in file for word in list_):
print 'Yahooo'

But how do I find the character index of the year in the absolute path?

Answer Source

Instead of using a generator expression (which has its own scope), use a traditional loop and then print the found word's index and break when you find a match:

list_ = ['2010', '2011','2012','2013','2014', '2015', '2016']
for word in list_:
    if word in file:
        print file.index(word)