-1

What is the fastest way to search a list of strings in a txt file in python?

I am loading the txt file, then splitting it's content by white spaces. It produces a list and then I am using : for eachString in StringList: if eachString in File: //do this

Subodh Deoli
  • 87
  • 1
  • 7

1 Answers1

0

Assuming you want to know the location:

str.find(sub[, start[, end]])

Return the lowest index in the string where substring sub is found, such that sub is contained in the slice s[start:end]. Optional

arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

If you don't care to know where the substring is located in the haystack string, just

substr in haystack

will return True or False, and that's all you want to know

Since you're already loading the entire file into memory, this seems like the best way to go. If it turns out that the file is larger than will fit in memory, or is actually a stream, then some other approach will be required. (but I don't want to get into that unless it's needed)

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
  • What if when I want to search a list of strings and display the common strings. txt file is very large and list can have more then 1000 values. – Subodh Deoli Sep 25 '13 at 15:10
  • You have a list of strings and you want to display the ones that appear in the file? Piece of cake. assuming you read your file as a string called contents, and your items are in a list called items, a list comp like this should do the job: [item for item in items if item in contents] This will produce a list containing each item i from items just if i appears in the string called contents. – Jon Kiparsky Sep 25 '13 at 15:25