0

I am on python 3.5 and want to find the matched words from a file. The word I am giving is awesome and the very first word in the .txt file is also awesome. Then why addedWord is not equal to word? Can some one give me the reason?

myWords.txt

awesome
shiny
awesome
clumsy

Code for matching

addedWord = "awesome"
        with open("myWords.txt" , 'r') as openfile:
                for word in openfile:
                    if addedWord is word:
                        print ("Match")

I also tried as :

 d = word.replace("\n", "").rstrip()
 a = addedWord.replace("\n", "").rstrip()
      if a is d:
          print ("Matched :" +word)

I also tried to get the class of variables by typeOf(addedWord) and typeOf(word) Both are from 'str' class but are not equal. Is any wrong here?

Amar
  • 855
  • 5
  • 17
  • 36
  • You're comparing using `is` which compares object identity rather than value. If they are in different places in memory with the same value, their identity is different. – Peter Wood Nov 11 '16 at 19:01
  • You should compare strings with `==`. Operator `is` checks if addedWord is the same object as word – Yevhen Kuzmovych Nov 11 '16 at 19:01
  • 2
    Related: http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python – Robᵩ Nov 11 '16 at 19:01

2 Answers2

1

Those two strings will never be the same object, so you should not use is to compare them. Use ==.

Your intuition to strip off the newlines was spot-on, but you just need a single call to strip() (it will strip all whitespace including tabs and newlines).

kindall
  • 178,883
  • 35
  • 278
  • 309
1

There are two problems with your code.

1) Strings returned from iterating files include the trailing newline. As you suspected, you'll need to .strip(), .rstrip() or .replace() the newline away.

2) String comparison should be performed with ==, not is.

So, try this:

    if addedWord == word.strip():
       print ("Match")
Robᵩ
  • 163,533
  • 20
  • 239
  • 308