Python: Reading from file, strings never equal

girisking

Honorable
Jun 20, 2012
6
0
10,510
Hello!

I'm having an issue with reading from a file and then comparing it to a string (Python 2.7.3). For the sake of the issue, I'm cutting out some specifics; I'm more interested in why potentially a string I'm reading in from a file is NEVER equal to a string I'm comparing it with.

I am reading from a document, which is comprised of lines that each only have 1 word on them. So,

The
train
went
...

for example. For each word, I want to see if it's the word "went." If it IS the word went, I do some action (unimportant). The problem I'm running into is, the if-statement below is NEVER firing for me (never returning true), so that branch of code never gets activated.

Python:
with open(document, 'r+') as textDocVariable:
     for i in textDocVariable:
           if i == "went":
                  #Do something


I've checked their values and types RIGHT BEFORE the if statement, and even with them both being type 'str' and value 'went' the if statement never fires.


I have very little experience with reading from documents, and I was wondering if there's something about the nature of reading from documents which will never let them be the same...

ADDITIONAL INFO: If I read the document into a string variable and split it, the the "went" will be equal; however, due to formatting issues with the original document, I would like to preserve whitespace that split() gets rid of.

Any insight would be much appreciated!

Thank you!
 

Ijack

Distinguished
The lines that you read from the textfile include newline characters, the string you are comparing it with doesn't. You need to strip the newline character from the end of the line before doing the comparison.