-1

My script finds other words along with the word like apple, such as app, me, ple, appl, etc. which in the search_word, but i don't want it, i need the script to define only the complete word which in the contents but not its parts.

apple - yes, i want to define this word.
app - no, i don't want to define this word.

list.txt contains:

apple

code:

with open('list.txt') as file:
    contents = file.read()
    search_word = input("enter a word you want to search in file: ")
    if search_word in contents:
        print ('word found')
    else:
        print ('word not found')

this not work:

if search_word == contents:
SkruDJ
  • 157
  • 8
  • Does this answer your question? [Python - Check If Word Is In A String](https://stackoverflow.com/questions/5319922/python-check-if-word-is-in-a-string) – mkrieger1 Apr 23 '22 at 20:50
  • @mkrieger1 The answers seem to talk about what OP is already doing... – wjandrea Apr 23 '22 at 20:54
  • What are `contents` and `search_word` exactly? It sounds like `contents` is something like `'apple'`, and when `search_word = 'app'`, you want it to say "word not found", but instead it says "word found". Is that right? Please provide a [mre]. You can [edit] your post. For more tips, see [ask]. – wjandrea Apr 23 '22 at 20:59
  • @wjandrea yes! I will approve my question. – SkruDJ Apr 23 '22 at 21:02
  • 1
    This might answer your question: [How to match a whole word with a regular expression?](/q/15863066/4518341) – wjandrea Apr 23 '22 at 21:08

2 Answers2

1

You may split the text using the space to avoid partial matching.

text_list = contents.split()
if search_word in text_list:
    print ('word found')
Esraa Abdelmaksoud
  • 1,307
  • 12
  • 25
0

This:

if search_word in contents:

Just change to:

if any(search_word==word.strip() for word in contents.split())

Thanks to the contribution in the comments!

SkruDJ
  • 157
  • 8