sys.stdin.readline() results in extra space send to stdout

Benjamin Rutt rutt at bmi.osu.edu
Mon Mar 6 11:19:06 EST 2006


There has been a problem that has been bugging me for a while for
reading input from standard in.  Consider the following simple program:

    #!/usr/bin/env python
    import sys
    print 'enter something: ',
    answer = sys.stdin.readline().strip()
    print 'you answered {%s}' % (answer)

When I run this interactively, the following happens:

    $ ~/tmp/foo.py 
    enter something: hi
     you answered {hi}

Notice the extra space before 'you'; I did not put it there.  It seems
that this problem can be avoided if I instead use the program:

    #!/usr/bin/env python
    import code
    answer = code.InteractiveConsole().raw_input('enter something: ')
    print 'you answered {%s}' % (answer)

Now, the output is:

    $ ~/tmp/foo.py 
    enter something: hi
    you answered {hi}

Is this a well-known problem?  Is it a bug?  I do not see why that
extra space is getting there in the first version.  Using the code
module seems a little dirty, when sys.stdin is available.  This is
python 2.4 on a Linux platform.  Thank you,
-- 
Benjamin Rutt



More information about the Python-list mailing list