The simplest way, but maybe not the most efficient for large files, is this:
# sample text for testing
# could come from a text file read like this:
infile = open("my_text.txt","r")
text = infile.read()
text = """\
My name is Fred Flintstone and I am a famous TV
star. I have as much authority as the Pope, I
just don't have as many people who believe it.
search = "Fred"
index = text.find(search)
print search, "found at index", index
my ouput (index is zero based) -->
Fred found at index 11
Note that find() only finds the first occurrence of the search word!
FWIW this will find all occurrences of a word in a string. Also note that if you are looking for "the" it will give a hit for "then". If you only want the word, you have to search with spaces added, " the " -assuming string.lower() and that punctuation is removed
while found > -1:
print word, "found at location", found
The string function find() can find a subtext within a larger text, as will re.findall(). The advantage of find() is that it will give you the location in the form of an index.
Thanks, but i'm a bit unsure on using the index since the length of data tends to change within the search area...
And sorry about not starting a new thread... cos in another hobby forum that i'm part of we try to post questions in a thread thats already started with a similar question so that other readers can also look back on the old answer.. i guess it depends on the forum :)
Thanks again guys. i'm new to DaniWeb and am loving it here! you guys are amazingly helpful!!!