Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

input() vs sys.stdin.read()

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.

like image 693
fogbit Avatar asked May 19 '11 08:05

fogbit


People also ask

What is a difference between input and SYS stdin readline ()?

The input takes input from the user but does not read escape character. The readline() also takes input from the user but also reads the escape character. It has a prompt that represents the default value before the user input.

Is stdin faster than input?

stdin. readline() is the fastest one when reading strings and input() when reading integers.

What does Sys stdin read () do?

It will read the source file line by line.

Is stdin faster than input Python?

stdin. readline is actually for Faster Inputs, because line reading through System STDIN (Standard Input) is faster in Python.


2 Answers

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.

like image 190
Michael Foukarakis Avatar answered Oct 04 '22 01:10

Michael Foukarakis


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.

like image 39
Duncan Avatar answered Oct 03 '22 23:10

Duncan