input() vs sys.stdin.read()

29,193

Solution 1

If you're on Windows, you'll notice that the result of input() when you type an 's' and Enter is "s\r". Strip all trailing whitespace from the result and you'll be fine.

Solution 2

You didn't say which version of Python you are using, so I'm going to guess you were using Python 3.2 running on Microsoft Windows.

This is a known bug see http://bugs.python.org/issue11272 "input() has trailing carriage return on windows"

Workarounds would include using a different version of Python, using an operating system that isn't windows, or stripping trailing carriage returns off any string() returned from input(). You should also be aware that iterating over stdin has the same problem.

Share:
29,193
fogbit
Author by

fogbit

Updated on July 31, 2020

Comments

  • fogbit
    fogbit almost 4 years
    import sys
    s1 = input()
    s2 = sys.stdin.read(1)
    
    #type "s" for example
    
    s1 == "s" #False
    s2 == "s" #True
    

    Why? How can I make input() to work properly? I tried to encode/decode s1, but it doesn't work.

    Thank you.

  • fogbit
    fogbit almost 13 years
    Yes, it's version 3.2 on windows. Thank you for explanation. Problem solved.
  • Duncan
    Duncan almost 13 years
    On the 'use a different version of Python' suggestion, I see that Python 3.2.1rc1 has been released, so if you don't mind using a release candidate for a minor point fix you can just upgrade to that version and the issue is fixed. See python.org/download/releases/3.2.1
  • Duncan
    Duncan almost 13 years
    Note that when commenting on my answer @fogbit confirmed they are using Python 3.2 where input() is the correct thing to use. Your advice would only apply for earlier versions of Python.
  • FlaPer87
    FlaPer87 almost 13 years
    You're right. When I posted my answer I didn't know the python version. I should've asked. Thanks ^^