Search code examples
pythonexcelstringpandasxlrd

Search for a specific string in excel sheet with number of index Python


Here I want search in an excel sheet with several strings where the excel sheet contains more than one index. If any one of the index of excel file contains those strings then it have to print true.

for i in sheet_data:
if search_string= "string1" or "string2" or "string3" etc.

   print true
else:
   print false

I have gone through this answer, but it search the string for a specific cell, but in my case the strings cell can't predicted and if any of the string contains in any cells of any index ,then it have to print true.

import xlrd
sheet_data = []   
wb = xlrd.open_workbook(Path_to_xlsx)
p = wb.sheet_names()
for y in p:
   sh = wb.sheet_by_name(y)
   for rownum in xrange(sh.nrows):
      sheet_data.append((sh.row_values(rownum)))

found_list = []
rows_to_be_saved = []
for i in sheet_data:
  if i[2] == "string1" or i[2] == "string2" or i[2] == "string3" or i[2] == "string4" or i[2] == "string5":
    found_list.append(i)
  else:
      rows_to_be_saved.append(i)

text_file = open("Output.txt", "w")
text_file.write(found_list)
text_file.close()

Solution

  • You have a list of data, where you want to search for some strings, so i can suggest the following to you.

    strings = ("string", "string2", "string3")
    for line in list:
        if any(s in line for s in strings):
            print("String Found")