Domanda

import sys
s1 = input()
s2 = sys.stdin.read(1)

#type "s" for example

s1 == "s" #False
s2 == "s" #True
.

Perché?Come posso rendere input() per funzionare correttamente? Ho provato a codificare / decodificare s1, ma non funziona.

Grazie.

È stato utile?

Soluzione

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.

Altri suggerimenti

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.

First, input is like eval(raw_input()) which means that everything you pass to it will be evalualted as a python expresion. I suggest you to use raw_input() instead.

I tested your code and they're equal for me:

import sys
s1 = input()
s2 = sys.stdin.read(1)

if s1==s2 and s1=="s":
    print "They're both equal s"

This is the output:

flaper87@BigMac:/tmp$ python test.py 
"s"
s
They're both equal s

Using sys.stdin.read(1) will read just 1 character from the stdin which means that if you pass "s" just the first " will be read. There's sys.stdin.readline() which reads the whole line (including the final \n).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top