What are the ways to find substring in string in Python? Which way is most effiecient?

I have used rfind, which is a string method to search for substrings. This code will search through the C:\ drive of a windows box, and look for all files containing '.avi'. Then it prints the full path of where the file containing '.avi' was found. Surprisingly tghis search feature was almost 3 times faster then using the windows serach feature

import os

for i in os.walk('c:/'):
    for j in i[2]:
        if j.rfind('.avi') != -1:
            base = os.path.abspath(i[0])
            print "%s\%s"%(base, j)

raw_input('enter retrun to exit')

the following code searched for all files larger then 1mb and contained the substring 'the'. This search took 18 seconds using this script. The Windows serach featrue took 48 seconds

import os

def pysearch(word):
   for i in os.walk('c:/'):
       for j in i[2]:
           if j.rfind(word) != -1:
               base = os.path.abspath(i[0])
               full_path = "%s\%s"%(base, j)
               if os.path.getsize(full_path) >= 1024000:
                   print full_path
               
               
pysearch('the')

raw_input('enter retrun to exit')

Hi!

I don't know if it's the most efficient way, but IMO it's the easiest:

>>> s = "lalahelloblabla"
>>> "hello" in s
True

@shanenin: In your first example, you check if the filename ends with ".avi". Well, Python has a function for this, called ... "endswith()" *tadaa* :)

>>> x = "lala.avi"
>>> x.endswith(".avi")
True

Regards, mawe

maybe I wanted to look for '.avi' in the middle of the file name :p just kidding, you are right endswith() is a nice way to do it :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.