Problems with user input
Steven Bethard
steven.bethard at gmail.com
Tue Nov 9 19:03:49 EST 2004
Florian Wilhelm <Florian.Wilhelm <at> web.de> writes:
>
> import sys
>
> print "Input: (y/N) ",
> input = sys.stdin.read(1)
> print "Hello World"
> print "Your input:", input
>
> produces this output...
>
> Input: (y/N) y
> Hello World
> Your input: y
>
> Can somebody explain why the whitespace char appears
> in front of "Hello World"???
This is the behavior of the print statement. For example:
>>> print "X", sys.stdin.read(1), "Y"
X1
1 Y
Every comma between two expressions in the print statement adds a space. As you
can see from the code above, the space isn't inserted until after the following
expression (sys.stdin.read(1)) is executed, and hence I get the space from the
print statement following the newline I inserted when I pressed <ENTER> after
typing 1.
If instead, you use sys.stdout.write, you get:
>>> def f():
... sys.stdout.write("X%s" % sys.stdin.read(1))
... sys.stdout.write("Y\n")
...
>>> f()
1
X1Y
sys.stdout.write doesn't insert spaces (unless you put spaces in the strings).
In general, if you want a particular format, you should use sys.stdout.write
instead of print, since the print statement has a number of such idiosyncracies.
Steve
More information about the Python-list
mailing list