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: if j.rfind('.avi') != -1: base = os.path.abspath(i) 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: if j.rfind(word) != -1: base = os.path.abspath(i) full_path = "%s\%s"%(base, j) if os.path.getsize(full_path) >= 1024000: print full_path pysearch('the') raw_input('enter retrun to exit')
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
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 :-)
We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.