0

Why does the following print "False"?

test.py:

import sys

if __name__ == "__main__":
    for text in sys.stdin:
        text_in_script = 'test'

        print(text == text_in_script)

Command line:

echo test | py -3 test.py

1 Answer 1

2

Because sys.stdin texts come with a new line character. It is more obvious when test.py is this:

import sys

if __name__ == "__main__":
    for text in sys.stdin:
        text_in_script = 'test'

        print("Input:  {}".format(text))
        print("Script: {}".format(text_in_script))
        print(text == text_in_script)

The solution would be to strip the new line character. The following will return "True":

import sys

if __name__ == "__main__":
    for text in sys.stdin:
        text_in_script = 'test'

        # warning: rstrip() removes all whitespace; see rstrip() docs for alternatives
        print(text.rstrip() == text_in_script)
Sign up to request clarification or add additional context in comments.

2 Comments

Updated question and answer.
If trailing whitespace might be important then use line.rstrip("\n") instead (note: it is portable if Python uses universal newlines mode (it does by default))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.