-1

I have below file contents

apples:100
books:100
pens:200
banana:300

I have below code to search string in file:

def search_string(file_search, search_string):

    search_output = []
    with open(file_search) as f:
        for line in f:
            if search_string in line:
                search_output.append(line)
     return search_output

To search apples:

  search_string("filename", "apples")

Some cases, I have to search two or three strings depends on requirement in same file, so I need to write separate functions, or can we achieve in same function. If same function can any one help

for two string search I have below code:

def search_string2(file_search, search_string1, search_strin2):

    search_output = []
    with open(file_search) as f:
        for line in f:
            if search_string1 in line or search_string2 in line:
                search_output.append(line)
     return search_output
preethy tulpi
  • 415
  • 1
  • 5
  • 15

2 Answers2

2

You can achieve this in a single function with varargs, by naming an argument with a preceding *, which collects all additional positional arguments into a tuple under that name. Then you use any with a generator expression to generalize the test to cover an unknown number of search strings:

def search_string(file_search, *search_strings):
    search_output = []
    with open(file_search) as f:
        for line in f:
            if any(searchstr in line for searchstr in search_strings):
                search_output.append(line)
    return search_output

This is fine for a smallish number of search strings, but if you need to handle a large volume of search strings, scanning a huge input or many small inputs, I'd suggest looking at more advanced optimizations, e.g. Aho-Corasick.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
-1

Just declare string2=None, then:

if str1 in line:
   ....
if str2 is not None and str2 in line:
   ....
wm3ndez
  • 721
  • 6
  • 10
  • This violates [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) (or if you prefer, [the Rule of Three](https://en.wikipedia.org/wiki/Rule_of_three_(computer_programming))), and only gets worse when you eventually need to accept three, four, etc., search strings (like many DRY violations committed in the name of "flexibility"). – ShadowRanger Feb 15 '18 at 02:48
  • @ShadowRanger completely agree with you, I missed the " two or three strings " part. – wm3ndez Feb 15 '18 at 14:43